【问题标题】:Append to dictionary file in json, python附加到json,python中的字典文件
【发布时间】:2015-10-22 01:57:29
【问题描述】:

所以我有一个文件python_dictionary.json,其中包含我想附加到的字典,而不必每次都打开。假设python_dictionary.json 仅包含:

{
    key1: value`
}

我想添加

new_dictionary=
    {
        key2:value2
    }

现在我在做:

with open('python_dictionary.json','a') as file:
    file.write(json.dumps(new_dictionary,indent=4))

这将创建一个字典:

{
    key1:value1
}
{
    key2:value2
}

这显然不是一本真正的字典。

我知道这一点:Add values to existing json file without rewriting it

但这涉及添加单个条目,我想做一个 json.dumps

【问题讨论】:

  • “但这涉及添加单个条目,我想做一个 json.dumps” - 我不确定你在这里的意思,你链接的方法是与json.dumps 完全兼容,您可以多次调用它。你需要它不做的什么?
  • 只是让您知道这也不是 JSON

标签: python json dictionary


【解决方案1】:

听起来您想从 json 加载字典,添加新的键值并将其写回。如果是这种情况,您可以这样做:

with open('python_dictionary.json','r+') as f:
    dic = json.load(f)
    dic.update(new_dictionary)
    json.dump(dic, f)

(模式是'r+'用于读写,而不是追加,因为你正在重写整个文件)

如果您想与 json.dumps 一起执行附加操作,我想您必须在附加之前从 json.dumps 字符串中删除第一个 {。比如:

with open('python_dictionary.json','a') as f:
    str = json.dumps(new_dictionary).replace('{', ',', 1)
    f.seek(-2,2)
    f.write(str)

【讨论】:

  • 在你的第一个例子中,不是json.dump(dic, f)吗? (因为dumps 只返回一个字符串,并不作用于文件对象)
【解决方案2】:

当 'r+' 或 'a' 选项无法正常工作时,您可以执行以下操作:

with open('python_dictionary.json','r') as f:
    dic = json.load(f)

dic.update(new_dictionary)

with open('python_dictionary.json','w') as f:
    json.dump(dic, f)

第一部分阅读现有的字典。然后用新字典更新字典。最后,你重写了整个更新的字典。

【讨论】:

    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多