【问题标题】:Loading JSON file from another directory in Python从 Python 中的另一个目录加载 JSON 文件
【发布时间】: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'),再添加一个.

标签: python json


【解决方案1】:

将路径更改为open('..\config\league.json', 'r'),再添加一个.

如果上面不行,使用abspath找到league.json的路径,传入open(path)函数

【讨论】:

  • 使用 open('..\config\league.json', 'r') 工作...谢谢!
【解决方案2】:

文件夹“config”需要位于文件夹“model”中,您的代码才能运行。否则将您的代码更改为

open('C:\Users\my_un\Documents\folder1\folder2\config\league.json', 'r')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-02
    • 2020-04-17
    • 1970-01-01
    • 2018-12-19
    • 2015-10-28
    • 2017-09-12
    • 2021-01-22
    • 2017-10-03
    相关资源
    最近更新 更多