所以我有一个文件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
答案 0 :(得分:5)
听起来你想从json加载字典,添加新的键值并将其写回。如果是这样的话,你可以这样做:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(模式为'r+'
用于读写,不附加,因为您正在重写整个文件)
如果你想和json.dump一起做追加的事情,我想你必须在追加之前从json.dumps字符串中删除第一个{
。类似的东西:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
答案 1 :(得分:0)
当“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)
第一部分阅读现有词典。然后用新字典更新字典。最后,你重写了整个更新的字典。