Django找不到我的应用程序文件夹中存储的文件

时间:2018-10-28 12:49:01

标签: python django

我有一个文件夹,它将json文件存储在django应用程序文件夹中,即test_data/data.json

在我的tests.py中,我尝试使用以下代码读取此文件:

with open('/test_data/data.json', 'r') as f:
    self.response_data = json.load(f)

但是,我不断遇到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: '/test_data/data.json'

我在做什么错?谢谢。

编辑:我尝试删除前导斜杠,但仍然出现相同的错误。

2 个答案:

答案 0 :(得分:0)

导入操作系统

尝试

app.post()

答案 1 :(得分:0)

如果要在靠近代码的目录中打开文件,通常会放置

import os
DIRNAME = os.path.dirname(__file__)  # the directory of this file

位于文件顶部。

然后,您可以使用

打开test_data子目录中的文件
with open(os.path.join(DIRNAME, 'test_data', 'data.json'), 'rb') as fp:
    self.response_data = json.load(fp)

您可能想以'rb'(二进制读)模式打开json文件,该文件应采用utf-8编码。