【发布时间】:2019-10-21 14:50:07
【问题描述】:
我想将字典添加到我的 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)
【问题讨论】:
-
你为什么不期待?
"a"ppend 模式添加到文件末尾。 -
其中哪一个会添加到列表中?
-
文件读写模式?他们都不是,他们不关心文件的布局。您需要解析旧内容,根据需要对其进行更新,然后将其写回文件中。
-
那我现在应该写什么呢?
-
@jonrsharpe 解释的哪一部分不清楚?
标签: python json python-3.x list dictionary