daydreamer
daydreamer

Reputation: 91969

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?

Upvotes: 2

Views: 2461

Answers (2)

kamalgill
kamalgill

Reputation: 121

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!

Upvotes: 3

Paulo Scardine
Paulo Scardine

Reputation: 77271

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().

Upvotes: 6

Related Questions