Python 如何将项目添加到JSON文件中存储的列表中
我想将字典添加到JSON文件中的列表中Python 如何将项目添加到JSON文件中存储的列表中,python,json,python-3.x,list,dictionary,Python,Json,Python 3.x,List,Dictionary,我想将字典添加到JSON文件中的列表中 reading = [] reading["game_review"] = { "name" : your_name, "time" : round(time_result, 2), "level" : level+1 } with open("stat.json", "a") as stats: json.dump(reading, stats) 每次我运行代码时,会在JSON文件中创建另一个字典,并将自己放在我已有的
reading = []
reading["game_review"] = {
"name" : your_name,
"time" : round(time_result, 2),
"level" : level+1
}
with open("stat.json", "a") as stats:
json.dump(reading, stats)
每次我运行代码时,会在JSON文件中创建另一个字典,并将自己放在我已有的字典旁边,我希望它将自己添加到字典中的列表中
编辑:
with open("stat.json", "r") as stat_read:
reading = json.loads(stat_read.read())
reading["game_review"] = {
"name" : your_name,
"time" : round(time_result, 2),
"level" : level+1
}
with open("stat.json", "a") as stats:
json.dump(reading, stats)
已解决:
with open("stats.json", "r") as stat_read:
reading = json.loads(stat_read.read())
reading["game_review"].append({
"name" : your_name,
"time" : round(time_result, 2),
"level" : level+1,
"date" : date
})
with open("stats.json", "w") as stats:
json.dump(reading, stats)
如果要这样做,请读取该文件,解析JSON内容,然后将JSON追加到列表中。然后重新写入文件。 假设一个JSON文件有以下内容
{'a':['b','c'],'d':'e'}
然后您可以执行以下操作
with open("data.json") as jfile:
current_data=json.load(jfile)
current_data['a'].append('f')
with open("data.json","w") as jfile:
json.dump(current_data,jfile)
文件中的最终内容将是
{'a':['b','c','f'],'d':'e'}
你为什么不这么想<代码>“a”p结束模式添加到文件的末尾。其中哪一个会添加到列表中?文件读取和写入模式?他们都不关心文件的布局。你需要解析旧内容,根据需要进行更新,然后将其写回文件。那么我现在应该写什么呢?@jornsharpe解释的哪一部分不清楚?