我有以下代码:
import json
with open("prefix.json", 'r+') as f:
data = json.load(f)
def changeprefix(id, prefix):
global data
if not id in data:
json.dump(data, open("prefix.json", "w"), indent = 4)
data[id] = prefix
else:
// Code to edit existing item
changeprefix("6", "?")
它会打开一个名为
prefix.json
的文件,我希望能够编辑现有项目,例如:
(Example.json)
{
"item": "234"
}
如何将
item
更改为 py 中的其他内容,例如更改为 text here
然后保存文件?
您所要做的就是分配给
data["item"]
,然后将所有data
写入prefix.json
!
data["item"] = "text here"
with open("prefix.json", "w") as f: # Makes sure to close the file
json.dump(data, f, indent=4)