Flask:如何在应用根目录读取文件?

24 投票
3 回答
50971 浏览
提问于 2025-04-17 15:35

我的Flask应用程序的结构如下:

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

当我运行 runserver.py 时,它会在 localhost:5000 启动服务器。
在我的 views.py 文件中,我尝试打开 english.txt 文件:

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

但是出现了错误 IOError: No such file or directory

我该如何访问这个文件呢?

3 个回答

3

Flask的app对象还有一个叫root_path的属性,用来找到根目录,还有一个instance_path属性,用于指向特定的app目录,这样就不需要用到os模块了。不过我还是喜欢@jpihl的回答。

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

这里有一个简单的替代方案,跟CppLearners的回答不同:

from flask import current_app

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

你可以在这里查看相关文档:Flask.open_resource

52

我觉得问题出在你路径里加了一个/。把这个/去掉,因为staticviews.py是在同一个层级上的。

我建议把settings.py放在和views.py同一个层级。很多Flask用户喜欢用__init__.py,但我个人不太喜欢。

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

如果你是这样设置的,可以试试这个:

#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')

现在在你的视图里,你可以简单地这样做:

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

根据你的需求调整路径和层级。

撰写回答