Flask: How to read a file in application root?

后端 未结 2 1774
情歌与酒
情歌与酒 2021-02-02 11:27

My Flask application structure looks like

application_top/
         application/
                    static/
                          english_words.txt
                 


        
2条回答
  •  一整个雨季
    2021-02-02 11:43

    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.

提交回复
热议问题