所以我有一个文件 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 加载字典,添加新的键值并将其写回。如果是这种情况,您可以这样做:
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)
关于python - 追加到json,python中的字典文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31728361/