如何使用 Python 更新 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24579896/
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 update a JSON file by using Python?
提问by user502052
I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json
containing the following data
我正在使用 Python 并且我有一个 JSON 文件,我想在其中更新与给定键相关的值。也就是说,我有my_file.json
包含以下数据
{"a": "1", "b": "2", "c": "3"}
and I would like to just change the value related to the b
key from 2
to 9
so that the updated file look as like:
我只想将与b
密钥相关的值从2
to更改为,9
以便更新后的文件如下所示:
{"a": "1", "b": "9", "c": "3"}
How can I make that?
我怎样才能做到这一点?
I tried the following but without success (the changes are not saved to the file):
我尝试了以下但没有成功(更改未保存到文件中):
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.close()
采纳答案by DrV
You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place.
您根本没有保存更改的数据。您必须先加载,然后修改,然后才保存。无法就地修改 JSON 文件。
with open('my_file.json', 'r') as f:
json_data = json.load(f)
json_data['b'] = "9"
with open('my_file.json', 'w') as f
f.write(json.dumps(json_data))
You may also do this:
你也可以这样做:
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between.
如果要确保安全,首先将新数据写入同一文件夹中的临时文件中,然后将临时文件重命名为原始文件。这样即使中间发生了一些事情,您也不会丢失任何数据。
If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant.
仔细想想,JSON 数据很难就地更改,因为数据长度不是固定的,而且更改可能非常显着。
回答by timgeb
You are almost there, you only have to write the updated json_data
back to the file. Get rid of f.close()
, as the with
statement will ensure that the file is closed. Then, issue
你快到了,你只需要把更新的写json_data
回文件。去掉f.close()
,因为该with
语句将确保文件已关闭。然后,发出
with open('my_file.json', 'w') as f:
f.write(json.dumps(json_data))
回答by Suhas Jadhav
This is simplest way to do the json file updation/writing. where you are creating instance of json file as 'f' and the writing the 'data' into the json file,
这是进行 json 文件更新/写入的最简单方法。您将 json 文件的实例创建为“f”并将“数据”写入 json 文件,
#write json file
with open('data.json', 'w') as f:
json.dump(data, f)
#Read json file
with open('data.json', 'r') as f:
json.load(data, f)