Python:只保存三个最新的分数



这是我为孩子们做的简短测验。程序的主体工作正常。但它必须将每个用户的三个最新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.")

如果要一次更新三个分数,则需要覆盖而不是追加:

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))

可能更容易腌制或 json 字典,并保留一个分数列表,将最后一个分数替换为最新的分数。

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.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)

最新更新