Monday, 15 August 2011

python - Flask: How to read a file in application root? -



python - Flask: How to read a file in application root? -

my flask application construction looks like

application_top/ application/ static/ english_words.txt templates/ main.html urls.py views.py runserver.py

when run runserver.py, starts server @ localhost:5000. in views.py, seek open file english.txt

f = open('/static/english.txt')

it gives error ioerror: no such file or directory

how can access file?

i think issue set / in path. remove / because static @ same level views.py.

i suggest making settings.py same level views.py or many flask users prefer utilize __init__.py don't.

application_top/ application/ static/ english_words.txt templates/ main.html urls.py views.py settings.py runserver.py

if how set up, seek this:

#settings.py import os # __file__ refers file settings.py app_root = os.path.dirname(os.path.abspath(__file__)) # refers application_top app_static = os.path.join(app_root, 'static')

now in views, can do:

import os settings import app_static open(os.path.join(app_static, 'english_words.txt')) f: f.read()

adjust path , level based on requirement.

python flask

No comments:

Post a Comment