在 pythonanywhere.com 上找不到文件

File not found on pythonanywhere.com

pythonanywhere.com 我有一个 Django 应用程序。这是 views.py:

def literature(request):
    module_dir = os.path.dirname(__file__)
    file_path = os.path.join(module_dir, 'literature.csv')
    with open(file_path, 'r') as f:
        ...

文件 literature.csv 与 views.py 位于同一目录。但是每次我尝试加载页面时,我都会得到 FileNotFoundError。同样的构造在本地服务器上正常工作。错误在哪里?

这个 os.path.dirname(__file__) 给你一个相对路径。在您的本地服务器上,恰好它对应于正确的路径。在 PythonAnywhere 上,使用 module_dir 的完整路径。像这样:os.path.abspath(os.path.dirname(__file__))