小编典典

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

flask

我的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

如何访问此文件?


阅读 1167

收藏
2020-04-07

共1个答案

小编典典

认为问题出在你/的道路上。删除,/因为static与处于同一级别views.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()

根据需要调整路径和级别。

2020-04-07