我正在写一个简单的python游戏,我有一个以下格式的文本文件,左边的键是玩家的名字,右边的值是玩家的名字。分数:
姓名134
下一个名称304958
等...
问题:如何以该格式读取文本文件并根据每行的值创建字典,一旦播放器退出程序,文件将使用最新的字典条目进行更新?
我已经有一些代码注释掉了我已经开始但却无法实现并开始工作。任何帮助表示赞赏。
这是我的代码:
# with open('scores.txt', 'r') as file:
# scores = {}
# for line in file:
# line = line.split()
# do stuff
# with open("scores.txt", "w") as f: # Save dictionary in file
# do stuff
答案 0 :(得分:1)
要加载该格式:
with open('scores.txt', 'r') as infile:
scores = {}
for line in infile:
name, _, score = line.rpartition(' ')
scores[name] = int(score)
保存该格式:
with open('scores.txt', 'w') as outfile:
for name, score in scores:
outfile.write('%s %s\n' % (name, score))
不过, penne12是正确的。您可以使用json
库来保存几行代码,以存储JSON而不是此特定文本格式。
答案 1 :(得分:0)
以下是评论中建议使用JSON的示例:
import json
def load_game_data():
data = None
with open('savegame.json', 'r') as savefile:
data = json.load(savefile)
return data
def save_game_data(data):
with open('savegame.json', 'w') as savefile:
json.dump(data, savefile)
# Store the game data as a dictionary:
data = { 'player_name' : 'wolfram', 'hp' : 8 }
save_game_data(data)
data = load_game_data()
print(data)
# prints {'player_name': 'wolfram', 'hp': 8}
print(data['player_name'])
print(data['hp'])
数据以JSON格式保存到磁盘,并作为字典从磁盘加载,易于使用。您需要添加代码错误处理,当然,这只是一个简单的说明。