【发布时间】:2021-07-04 21:22:24
【问题描述】:
有没有办法将另一个值添加到键中,而不是使用 python 在 json 文件中替换它? 我尝试使用“a”而不是“w”,但它创建了一组不同的字典,我收到一条错误消息,说 Json 只允许一个顶级值
import json
web=input('web:')
username=input('us:')
pw=input('pw')
account_data= {web: {'Email': username,'Password': pw}}
try:
with open('trial.json', 'r') as file:
# save the previous data in json
data = json.load(file)
# update the json by appending the newer data into old data
data.update(account_data)
except FileNotFoundError:
with open('trial.json', 'w') as file:
# create data.json if it doesnt exist
json.dump(account_data, file, indent=4)
else:
with open('trial.json', 'w') as file:
# replace old json file with new one
json.dump(data, file, indent=4)
输出:
{
"face": {
"Email": "asdqweerqr",
"Password": "dregtertsdf"
},
"fasd": {
"Email": "wqe",
"Password": "asdf"
}
}
输出总是替换现有的键值对。 谢谢
【问题讨论】:
-
还提供您期望的结果。
标签: json python-3.x dictionary