Flask: How to read a file in application root?

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?

1

3 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.

2

Here's a simple alternative to CppLearners answer:

from flask import current_app
with current_app.open_resource('static/english_words.txt') as f: f.read()

See the documentation here: Flask.open_resource

The flask app also has a property named root_path to resolve the root directory as well as an instance_path property for the particular app directory without requiring the os module, though I like @jpihl's answer.

with open(f'{app.root_path}/static/english_words.txt', 'r') as f: f.read()

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like