[英]how to read and write one specific line in json file python
the json file looks like this: json 文件如下所示:
{
"Me": {
"Age": 0,
"Location": 0,
"Friends": 0,
"Family": 0
},
"You": {
"Age": 0,
"Location": 0,
"Friends": 0,
"Family": 0
}
}
To read ["Me"]["Age"] and assign it to a variable I can use:要读取 ["Me"]["Age"] 并将其分配给我可以使用的变量:
f = open('info.json')
data = json.load(f)
ageinfo = data["Me"]["Age"]
now, if the variable ageinfo
updates, I want to send it back to the json file and save it.现在,如果变量ageinfo
更新,我想将其发送回 json 文件并保存。 Im not exactly sure how to achieve this, maybe using json.dump?我不确定如何实现这一点,也许使用 json.dump? If anyone could help that would be greatly appreciated.如果有人可以提供帮助,将不胜感激。
yes you can use the json.dump function to do that.是的,您可以使用 json.dump function 来做到这一点。 Imagine you change the content of your dict想象一下,您更改了 dict 的内容
ageinfo = "new_value"
data["Me"]["Age"] = ageinfo
If you want to write it in a file info.json for instance the code would look like this:例如,如果您想将其写入文件 info.json,代码将如下所示:
with open('info.json', 'w') as outfile:
json.dump(data, outfile)
This will update the file info.json with the content of your dict (or create it if it does not exist)这将使用您的 dict 的内容更新文件 info.json(或者如果它不存在则创建它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.