用Python编辑JSON文件的简单方法是什么?
这里有一些类似的问题,但我找不到能满足我需求的答案。
我正在使用的代码如下(python 2.75):(编辑,更新以包含建议以提高清晰度):
def write_json(entry):
current_players = []
with open("Dota2data.txt","r+") as outfile:
data = json.load(outfile)
for member in entry.players:
current_players.append(member['account_id'])
data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
json.dump(data, outfile)
outfile.close()
pass
我基本上是想在每次运行这个函数时,在'matches'这个键里添加一个新的比赛实例(这个函数是在加载新比赛时调用的)。
不过,正如你们可能注意到的,这样做每次都会用最新的结果替换掉文本文件。
我知道可以通过追加的方式在每一行添加新比赛,但因为我有点固执,我想把数据放在'matches'字段里。这可能吗?
谢谢!
补充:我想说,今晚是我第一次尝试这个,我对python也很陌生。
那个答案帮了我很大的忙,我现在有了动力去完成这个。谢谢你的帮助!作为参考,最终的代码如下。
def write_json(entry):
current_players = []
with open("Dota2data.txt","r+") as infile:
data = json.load(infile)
for member in entry.players:
current_players.append(member['account_id'])
data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
infile.close()
with open("Dota2data.txt","r+") as outfile:
json.dump(data, outfile)
outfile.close()
pass
相关问题:
3 个回答
0
def update_file(path, entry):
with open(path) as infile:
data = json.load(infile)
current_players = [member['account_id'] for member in entry.players]
data["matches"].append({
"match": entry.match_id,
"winner": entry.radiant_win,
"players": current_players
})
with open(path, "w") as outfile:
json.dump(data, outfile)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。
1
更新:把你的引号改成双引号 "",不要用单引号 '',这样在用 json.loads 的时候才不会出错。或者,你也可以用 ast.literal_eval() 来解决这个问题。
更新2:让我再解释一下,JSON 语法里是用双引号的,而 Python 则可以用单引号或双引号。如果你在调用 json.loads 的时候,就要用双引号来写你的 JSON。如果你想用单引号,那就得用 ast.literal_eval。记得要 import ast。
0
编辑:在做任何事情之前,先加载文件。
with open("Dota2data.txt","r+") as outfile:
当然,首先我们要把这个json文件加载到一个对象里。
data = json.load(outfile)
然后,在 'matches' 里面添加一个新的属性,作为一个字典。
data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
最后,输出这个文件。
json.dump(data, outfile)
完整代码:
def write_json(entry):
with open("Dota2data.txt","r") as infile:
for member in entry.players:
current_players = current_players.append(member['account_id'])
data = json.load(infile)
infile.close
data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
with open("Dota2data.txt","w") as outfile:
json.dump(data, outfile)
outfile.close()