【发布时间】:2020-09-20 02:57:08
【问题描述】:
我正在尝试从名为 run_test.py 的 python 文件中读取名为 League.json 的 JSON 文件。 JSON 文件位于不同的目录中。我在 Visual Studio 中运行 Windows 10 和 python 3.8.6。
- 我运行python文件的目录是:C:\Users\my_un\Documents\folder1\folder2\model\run_test.py
- 我试图从中加载 json 文件的目录是: C:\Users\my_un\Documents\folder1\folder2\config\league.json
根据我找到的文档,以下代码应该可以工作,但我不断收到错误消息:FileNotFoundError: [Errno 2] No such file or directory: 'config\league.json'。
当我将league.json 移动到与python 文件相同的目录并将打开位置更改为:'.\league.json' 时,这确实运行成功。
我做错了什么?我的代码如下。提前致谢。
import json
with open('.\config\league.json', 'r') as f:
config = json.load(f)
print (len(config))
【问题讨论】:
-
将路径更改为
open('..\config\league.json', 'r'),再添加一个.