Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to read a file in application root?

Tags:

My Flask application structure looks like

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

When I run the runserver.py, it starts the server at localhost:5000. In my views.py, I try to open the file english.txt as

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

It gives error IOError: No such file or directory

How can I access this file?

like image 663
daydreamer Avatar asked Feb 12 '13 05:02

daydreamer


People also ask

How do you get the root path in Flask?

To get the root path of a Python Flask application, we can use the app. instance_path property. to get the Flask app instance's folder with app. instance_path .

How do I access static files in Flask?

Flask – Static Files Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application. A special endpoint 'static' is used to generate URL for static files.


1 Answers

I think the issue is you put / in the path. Remove / because static is at the same level as views.py.

I suggest making a settings.py the same level as views.py Or many Flask users prefer to use __init__.py but I don't.

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

If this is how you would set up, try this:

#settings.py import os # __file__ refers to the file settings.py  APP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_top APP_STATIC = os.path.join(APP_ROOT, 'static') 

Now in your views, you can simply do:

import os from settings import APP_STATIC with open(os.path.join(APP_STATIC, 'english_words.txt')) as f:     f.read() 

Adjust the path and level based on your requirement.

like image 137
CppLearner Avatar answered Sep 26 '22 18:09

CppLearner