[英]Append to dictionary file in json, python
So I have a file python_dictionary.json
which contains a dictionary which I want to append to without having to open each time.所以我有一个文件
python_dictionary.json
,其中包含一个我想附加到的字典,而不必每次都打开。 Let's say that python_dictionary.json
contains only:假设
python_dictionary.json
只包含:
{
key1: value`
}
and I want to add我想补充
new_dictionary=
{
key2:value2
}
Right now I am doing:现在我正在做:
with open('python_dictionary.json','a') as file:
file.write(json.dumps(new_dictionary,indent=4))
This creates a dictionary as:这将创建一个字典:
{
key1:value1
}
{
key2:value2
}
which is obviously not a real dictionary.这显然不是一本真正的字典。
I am aware of this: Add values to existing json file without rewriting it我知道这一点: 将值添加到现有的 json 文件而不重写它
but this deals with adding a single entry, I want to do a json.dumps但这涉及添加单个条目,我想做一个 json.dumps
Sounds like you want to load a dictionary from json, add new key values and write it back.听起来您想从 json 加载字典,添加新的键值并将其写回。 If that's the case, you can do this:
如果是这种情况,您可以这样做:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(mode is 'r+'
for reading and writing, not appending because you're re-writing the entire file) (模式是
'r+'
用于读取和写入,不追加,因为您正在重写整个文件)
If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first {
from the json.dumps string before appending.如果你想和 json.dumps 一起做追加的事情,我猜你必须在追加之前从 json.dumps 字符串中删除第一个
{
。 Something like:就像是:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
When the 'r+' or 'a' option does not work properly, you can do the following:当 '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)
The first part read the existing dictionary.第一部分阅读现有词典。 Then you update the dictionary with the new dictionary.
然后用新字典更新字典。 Finally, you rewriting the whole updated dictionary.
最后,您重写整个更新的字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.