【问题标题】:Python reading dictionary from file [duplicate]Python从文件中读取字典[重复]
【发布时间】:2021-05-14 17:39:05
【问题描述】:

我正在尝试从一个看起来像这样的 JSON 文件中读取字典。

{"@C": "C:\\Users\\user\\examplefolder}

我想将字典从文件加载到filepath_dict。我目前正在使用这种方法来尝试这个,但是它拒绝加载任何不是字符串的东西。

import json


with open("filepaths.json", "r") as file:
    file.write(json.loads(filepaths_dict))

如何将 JSON 字典加载到 python 中?

【问题讨论】:

  • 我错过了电话;费尔南多抓住了它。它只加载字符串,因为您调用了json.loads(加载字符串)。

标签: python json


【解决方案1】:

使用json.load

with open("filepaths.json", "r") as f:
    filepaths_dict = json.load(f)

json.loads: 会取一个字符串

json.load: 会拿档案

还要小心使用“文件”这个词作为变量,你会覆盖内置的file 函数。

【讨论】:

  • 非常感谢,我会尽快接受答复
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 2016-02-26
  • 2013-01-21
  • 2021-08-20
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多