如何在 Python 中追加 json 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18980039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append in a json file in Python?
提问by PythonEnthusiast
I have the a json file whose contents is {"67790": {"1": {"kwh": 319.4}}}. Now I create a dictionary a_dictwhich I need to append it into the json file. I tried the following but was not able to do it correctly. Where I'm going wrong?
我有一个 json 文件,其内容是{"67790": {"1": {"kwh": 319.4}}}. 现在我创建了一个字典a_dict,我需要将它附加到 json 文件中。我尝试了以下操作,但无法正确执行。我哪里错了?
with open(DATA_FILENAME, 'a') as f:
json_obj = json.dump(a_dict, json.load(f)
f.write(json_obj)
f.close()
采纳答案by alecxe
Assuming you have a test.jsonfile with the following content:
假设您有一个test.json包含以下内容的文件:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will loadthe json file, update the data inside using dict.update()and dumpinto the test.jsonfile:
接着,下面的代码将loadJSON文件,里面更新使用数据dict.update()和dump到test.json文件:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json, you'll have:
然后,在 中test.json,您将拥有:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
希望这是你想要的。
回答by Nicolas Barbey
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
您需要使用 a_dict 更新 json.load 的输出,然后转储结果。您不能附加到文件,但需要覆盖它。
回答by kodeslacker
json_obj=json.dumps(a_dict, ensure_ascii=False)

![OSError: [Errno 2] 在 Django 中使用 python 子进程时没有这样的文件或目录](/res/img/loading.gif)