Getting exception while opening files in flask











up vote
0
down vote

favorite












I'm getting error when i make postman request to my api when trying to read files from a directory.



    cwd = os.getcwd()
print(cwd)
cwd = cwd.replace('\','/')
print(cwd)
path = cwd + "/training_data/"
print(path)
try:

for files in os.listdir(path):
data = open(path + files,'r').readlines()
bot.train(data)

except Exception as e:
return jsonify("Error while opening file",path,cwd,os.listdir(path))


I'm getting the following exception:



[
"Error while opening file",
"C:/Users/RakeshS/Desktop/app/training_data/",
"C:/Users/RakeshS/Desktop/app",
[
"code.txt",
"deputation1.txt",
"football.txt",
"Greeting.txt",
"internetaccess.txt",
"intravels.txt",
"sentiment.txt",
"system.txt"
]]


Why is it not able to open the file and read data when i'm getting all the list of files inside the directory?










share|improve this question






















  • Did you tried to print the actual exception?
    – Abdul Niyas P M
    Nov 22 at 14:06










  • yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
    – alia
    Nov 22 at 14:14










  • Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
    – Abdul Niyas P M
    Nov 22 at 14:18

















up vote
0
down vote

favorite












I'm getting error when i make postman request to my api when trying to read files from a directory.



    cwd = os.getcwd()
print(cwd)
cwd = cwd.replace('\','/')
print(cwd)
path = cwd + "/training_data/"
print(path)
try:

for files in os.listdir(path):
data = open(path + files,'r').readlines()
bot.train(data)

except Exception as e:
return jsonify("Error while opening file",path,cwd,os.listdir(path))


I'm getting the following exception:



[
"Error while opening file",
"C:/Users/RakeshS/Desktop/app/training_data/",
"C:/Users/RakeshS/Desktop/app",
[
"code.txt",
"deputation1.txt",
"football.txt",
"Greeting.txt",
"internetaccess.txt",
"intravels.txt",
"sentiment.txt",
"system.txt"
]]


Why is it not able to open the file and read data when i'm getting all the list of files inside the directory?










share|improve this question






















  • Did you tried to print the actual exception?
    – Abdul Niyas P M
    Nov 22 at 14:06










  • yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
    – alia
    Nov 22 at 14:14










  • Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
    – Abdul Niyas P M
    Nov 22 at 14:18















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm getting error when i make postman request to my api when trying to read files from a directory.



    cwd = os.getcwd()
print(cwd)
cwd = cwd.replace('\','/')
print(cwd)
path = cwd + "/training_data/"
print(path)
try:

for files in os.listdir(path):
data = open(path + files,'r').readlines()
bot.train(data)

except Exception as e:
return jsonify("Error while opening file",path,cwd,os.listdir(path))


I'm getting the following exception:



[
"Error while opening file",
"C:/Users/RakeshS/Desktop/app/training_data/",
"C:/Users/RakeshS/Desktop/app",
[
"code.txt",
"deputation1.txt",
"football.txt",
"Greeting.txt",
"internetaccess.txt",
"intravels.txt",
"sentiment.txt",
"system.txt"
]]


Why is it not able to open the file and read data when i'm getting all the list of files inside the directory?










share|improve this question













I'm getting error when i make postman request to my api when trying to read files from a directory.



    cwd = os.getcwd()
print(cwd)
cwd = cwd.replace('\','/')
print(cwd)
path = cwd + "/training_data/"
print(path)
try:

for files in os.listdir(path):
data = open(path + files,'r').readlines()
bot.train(data)

except Exception as e:
return jsonify("Error while opening file",path,cwd,os.listdir(path))


I'm getting the following exception:



[
"Error while opening file",
"C:/Users/RakeshS/Desktop/app/training_data/",
"C:/Users/RakeshS/Desktop/app",
[
"code.txt",
"deputation1.txt",
"football.txt",
"Greeting.txt",
"internetaccess.txt",
"intravels.txt",
"sentiment.txt",
"system.txt"
]]


Why is it not able to open the file and read data when i'm getting all the list of files inside the directory?







python flask postman






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 14:05









alia

1026




1026












  • Did you tried to print the actual exception?
    – Abdul Niyas P M
    Nov 22 at 14:06










  • yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
    – alia
    Nov 22 at 14:14










  • Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
    – Abdul Niyas P M
    Nov 22 at 14:18




















  • Did you tried to print the actual exception?
    – Abdul Niyas P M
    Nov 22 at 14:06










  • yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
    – alia
    Nov 22 at 14:14










  • Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
    – Abdul Niyas P M
    Nov 22 at 14:18


















Did you tried to print the actual exception?
– Abdul Niyas P M
Nov 22 at 14:06




Did you tried to print the actual exception?
– Abdul Niyas P M
Nov 22 at 14:06












yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
– alia
Nov 22 at 14:14




yes getting this 'charmap' codec can't decode byte 0x9d in position 1459: character maps to <undefined>'
– alia
Nov 22 at 14:14












Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
– Abdul Niyas P M
Nov 22 at 14:18






Why is it not able to open the file and read data when i'm getting all the list of files inside the directory? The issue is not with the FilePermission. That is why you were able to list the files on the directory. The issue is with the file encoding. You should pass the encoding of the file with open(path + files,'r', encoding="your_file_encoding"). I will also recommend you to read this answer.
– Abdul Niyas P M
Nov 22 at 14:18














1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Here is complete solution to your problem:



from flask import Flask, jsonify
import os
app = Flask(__name__)


@app.route('/')
def hello_world():
cwd = os.getcwd()
path = os.path.join(os.getcwd(), 'training_data')
try:
for file in os.listdir(path):
path_and_file = os.path.join(path, file)
data = open(path_and_file, 'r').readlines()
print(data) # To print everything from a file
return jsonify("Files successfully opened", path, cwd, os.listdir(path))

except:
return jsonify("There was error opening files", path, cwd, os.listdir(path))


if __name__ == '__main__':
app.run()


Here is the output:



Response of postman



Explanation:



In my example, I put it on / route, but you can put it where ever you want.



Whenever I go to / route, I get JSON response. os.getcwd() gets me current directory, but I join two paths using os.path.join() function. From python documentation:




Join one or more path components intelligently.




You can read more on python documentation. Next, since I get the path to training_data, I need to join again path to training_data and file. And I return JSON data. If anything goes wrong, you can print traceback in except clause and also return data, so that flask doesn't raise error for returning no response to the user.



P.S.



training_data folder is in a same level as a your flask application.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432713%2fgetting-exception-while-opening-files-in-flask%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Here is complete solution to your problem:



    from flask import Flask, jsonify
    import os
    app = Flask(__name__)


    @app.route('/')
    def hello_world():
    cwd = os.getcwd()
    path = os.path.join(os.getcwd(), 'training_data')
    try:
    for file in os.listdir(path):
    path_and_file = os.path.join(path, file)
    data = open(path_and_file, 'r').readlines()
    print(data) # To print everything from a file
    return jsonify("Files successfully opened", path, cwd, os.listdir(path))

    except:
    return jsonify("There was error opening files", path, cwd, os.listdir(path))


    if __name__ == '__main__':
    app.run()


    Here is the output:



    Response of postman



    Explanation:



    In my example, I put it on / route, but you can put it where ever you want.



    Whenever I go to / route, I get JSON response. os.getcwd() gets me current directory, but I join two paths using os.path.join() function. From python documentation:




    Join one or more path components intelligently.




    You can read more on python documentation. Next, since I get the path to training_data, I need to join again path to training_data and file. And I return JSON data. If anything goes wrong, you can print traceback in except clause and also return data, so that flask doesn't raise error for returning no response to the user.



    P.S.



    training_data folder is in a same level as a your flask application.






    share|improve this answer

























      up vote
      1
      down vote



      accepted










      Here is complete solution to your problem:



      from flask import Flask, jsonify
      import os
      app = Flask(__name__)


      @app.route('/')
      def hello_world():
      cwd = os.getcwd()
      path = os.path.join(os.getcwd(), 'training_data')
      try:
      for file in os.listdir(path):
      path_and_file = os.path.join(path, file)
      data = open(path_and_file, 'r').readlines()
      print(data) # To print everything from a file
      return jsonify("Files successfully opened", path, cwd, os.listdir(path))

      except:
      return jsonify("There was error opening files", path, cwd, os.listdir(path))


      if __name__ == '__main__':
      app.run()


      Here is the output:



      Response of postman



      Explanation:



      In my example, I put it on / route, but you can put it where ever you want.



      Whenever I go to / route, I get JSON response. os.getcwd() gets me current directory, but I join two paths using os.path.join() function. From python documentation:




      Join one or more path components intelligently.




      You can read more on python documentation. Next, since I get the path to training_data, I need to join again path to training_data and file. And I return JSON data. If anything goes wrong, you can print traceback in except clause and also return data, so that flask doesn't raise error for returning no response to the user.



      P.S.



      training_data folder is in a same level as a your flask application.






      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Here is complete solution to your problem:



        from flask import Flask, jsonify
        import os
        app = Flask(__name__)


        @app.route('/')
        def hello_world():
        cwd = os.getcwd()
        path = os.path.join(os.getcwd(), 'training_data')
        try:
        for file in os.listdir(path):
        path_and_file = os.path.join(path, file)
        data = open(path_and_file, 'r').readlines()
        print(data) # To print everything from a file
        return jsonify("Files successfully opened", path, cwd, os.listdir(path))

        except:
        return jsonify("There was error opening files", path, cwd, os.listdir(path))


        if __name__ == '__main__':
        app.run()


        Here is the output:



        Response of postman



        Explanation:



        In my example, I put it on / route, but you can put it where ever you want.



        Whenever I go to / route, I get JSON response. os.getcwd() gets me current directory, but I join two paths using os.path.join() function. From python documentation:




        Join one or more path components intelligently.




        You can read more on python documentation. Next, since I get the path to training_data, I need to join again path to training_data and file. And I return JSON data. If anything goes wrong, you can print traceback in except clause and also return data, so that flask doesn't raise error for returning no response to the user.



        P.S.



        training_data folder is in a same level as a your flask application.






        share|improve this answer












        Here is complete solution to your problem:



        from flask import Flask, jsonify
        import os
        app = Flask(__name__)


        @app.route('/')
        def hello_world():
        cwd = os.getcwd()
        path = os.path.join(os.getcwd(), 'training_data')
        try:
        for file in os.listdir(path):
        path_and_file = os.path.join(path, file)
        data = open(path_and_file, 'r').readlines()
        print(data) # To print everything from a file
        return jsonify("Files successfully opened", path, cwd, os.listdir(path))

        except:
        return jsonify("There was error opening files", path, cwd, os.listdir(path))


        if __name__ == '__main__':
        app.run()


        Here is the output:



        Response of postman



        Explanation:



        In my example, I put it on / route, but you can put it where ever you want.



        Whenever I go to / route, I get JSON response. os.getcwd() gets me current directory, but I join two paths using os.path.join() function. From python documentation:




        Join one or more path components intelligently.




        You can read more on python documentation. Next, since I get the path to training_data, I need to join again path to training_data and file. And I return JSON data. If anything goes wrong, you can print traceback in except clause and also return data, so that flask doesn't raise error for returning no response to the user.



        P.S.



        training_data folder is in a same level as a your flask application.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 14:59









        Dinko Pehar

        7992324




        7992324






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432713%2fgetting-exception-while-opening-files-in-flask%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            How to ignore python UserWarning in pytest?

            Alexandru Averescu