这是我为孩子们做的简短测验。该程序的主体工作正常。但它必须将每个用户的三个最新correctAnswers
保存到.txt
文件中,删除旧分数。
我花了很长时间试图找出如何使用JSON或者Pickle作为我的代码,但我不知道如何将它们用于我的代码。任何帮助将不胜感激。
if usersGroup == a:
with open("groupA.txt","a+") as f:
f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersGroup == b:
with open("groupB.txt","a+") as f:
f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersGroup == c:
with open("groupC.txt","a+") as f:
f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
print("Sorry, we can not save your data as the group you entered is not valid.")
答案 0 :(得分:2)
如果您要一次更新三个分数,则需要覆盖不附加:
open("groupA.txt","w")
保持上一次运行的最后两次并写下最新的单一分数:
with open("groupA.txt","a+") as f:
sores = f.readlines()[-2:] # get last two previous lines
with open("groupA.txt","w") as f:
# write previous 2
f.writelines(scores)
# write latest
f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
可能更容易pickle或json dict并保留一个分数列表,用最新的分数替换最后一个分数。
import pickle
from collections import defaultdict
with open('scores.pickle', 'ab') as f:
try:
scores = pickle.load(f)
except ValueError:
scores = defaultdict(list)
# do your logic replacing last score for each name or adding names
with open('scores.pickle', 'wb') as f:
# pickle updated dict
pickle.dump(f,scores)
如果您希望人类可读的格式使用json.dump
和普通的dict,您可以使用dict.setdefault而不是使用defaultdict的功能:
import json
with open('scores.json', 'a') as f:
try:
scores = json.load(f)
except ValueError:
scores = {}
# add user if not already in the dict with a list as a value
scores.setdefault(name,[])
# just append the latest score making sure when you have three to relace the last
scores[name].append(whatever)
# do your logic replacing last score for each name or adding names
with open('scores.json', 'w') as f:
json.dump(scores,f)