简体   繁体   中英

GoogleAppEngine: How to read text file using python?

My project structure looks like

flask-appengine-template/
                        docs/
                        licenses/
                        src/
                            application/
                                        static/
                                        templates/
                                        models.py
                                        settings.py
                                        urls.py
                                        views.py
                                        english.txt
                        libs/
                            bs4/
                         app.yaml
                         src.py

in my views.py , I have a function that reads the file english.txt

      for words in open('english.txt', 'r').readlines():
            stopwords.append(words.strip())

When I run this on local environment , I see error in logs as

(<type 'exceptions.IOError'>, IOError(13, 'file not accessible'), <traceback object at 0x10c457560>)

How do I read this file in Google App Engine?

If english.txt is just a list of words, I suggest converting the list of words to a python list, so you can just import it.

If english.txt has more complex data, move it to bigtable or other database available to your app.

AppEngine is a very crippled environment compared to a standard VPS, I tend to avoid functions that operates over the underlying OS like open() .

You'll need to use os.path to get the proper reference to the file path, something along the lines of:

def read_words():
    import os.path
    folder = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(folder, 'english.txt')
    for words in open(file_path, 'r').readlines():
        stopwords.append(words.strip())

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM