I have my webapp written in Python running on Google App Engine; so far only testing in my localhost. My script needs to read text files located in various directories. So in my Python script I would simply use os.chdir("./"+subdirectory_name) and then start opening and reading the files and using the text for analysis. However I cannot do that when trying to move it over to App Engine.

I assume I need to make some sort of changes to app.yaml but I'm stuck after that. Can anyone walk me through this somewhat thoroughly?

From the answer below, I was able to fix this part, I have a followup question about the app.yaml structure though. I have my folder set up like the following, and I'm wondering what I need to put in my app.yaml file to make it work when I deploy the project (it works perfectly on localhost right now).

Main_Folder:

  • python_my_app.py
  • app.yaml
  • text_file1
  • text_file2
  • text_file3
  • subfolder1_with_10_text_files_inside
  • subfolder2_with_10_text_files_inside
  • subfolder3_with_10_text_files_inside

...how do I specify this structure in my app.yaml and do I need to change anything in my code if it works right now on localhost?

有帮助吗?

解决方案

You don't need to change your working directory at all to read files. Use absolute paths instead.

Use the current file location as the starting point, and resolve all relative paths from there:

import os.path

HERE = os.path.dirname(os.path.abspath(__file__))

somefile = os.path.abspath(os.path.join(HERE, 'subfolder1_with_10_text_files_inside /somefile.txt'))

If you want to be able to read static files, do remember to set the application_readable flag on these, as Google will otherwise only upload them to their content delivery network, not to the app engine.

其他提示

You can package your text files inside your application and then do something like this:

    path = os.path.join(os.path.dirname(__file__), 'subdir', 'file')
    file = open(path)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top