Python: Only saving three latest scores
Question: This is my short quiz made for children. The main body of the program works
fine. But it must save the three latest `correctAnswers` for each user onto a
`.txt` file, deleting the old scores.

I've spent quite some time trying to work out how to use JSON or Pickle for my
code but I have no idea how to use them for my code. Any help will be
appreciated.

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


Answer: You need to overwrite not append if you are updating the three scores at once:

    
    
    open("groupA.txt","w") 
    

To keep the last two from the previous run and write the latest single score:

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

Might be easier pickle or json a dict and keep a list of scores replacing the
last score with the latest.

    
    
    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)
    

If you want human readable format use `json.dump` and a normal dict, you can
use dict.setdefault instead of the functionality of using a 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)
    

