简体   繁体   中英

store last 3 scores with the use of pickle or json?

I have made a quiz which allows the users to enter their name and have their name and score saved to a specific file according to the class they are in. However, I need the file to only store the last 3 most recent scores. I have shown one of the attempts below but it still wont store only the 3 most recent scores. i have researched other ways and have realised i might need pickle or json to write the content of 3_scores to the text file? so i would like if one of you guys could explain and possibly write a solution with the use of pickle or json if needed because i have tried and still can't do it.

   if classselection ==1:
    File=open("1.txt","a")
    File.write(names+","+str(score)+"\n")
    File.close()
    classselection=str(classselection)
with open("1.txt" , "a") as my_class:
    my_class.write(names+","+str(score)+"\n")
with open("1.txt" , "r+")as file:
    file.seek(0)
    scores = file.readlines()
3_scores = {}
for line in scores:
    names, score = line.split(',')
    score = int(score)
    if names not in 3_scores:
        3_scores[names] = []
    3_scores[names].append(score)
    if len(3_scores[names]) > 3:
        3_scores[names].pop(0)

then, i tried using json, so straight after the code above i wrote

    import json
    d=user_scores
    json.dump(d,open('A.txt','w'))
    d2=json.load(open('A.txt'))
    print (d2)

however, this didnt work as

 names, score = line.split(',')
 ValueError: too many values to unpack (expected 2)

EDIT HI now what is printed is

 {' lol': [5]}
 {' sid': [8], ' lol': [5]}
 {' sid': [8, 8], ' lol': [5]}
 {' lok': [1], ' sid': [8, 8], ' lol': [5]}
 {' lok': [1, 1], ' sid': [8, 8], ' lol': [5]}
 {' lok': [1, 1], ' sid': [8, 8], ' lojhg': [0], ' lol': [5]}
 {' lok': [1, 1], ' sid': [8, 8], ' lojhg': [0, 0], ' lol': [5]}

which isnt right. so please, i would appreciate if anyonecould provide a solution

**also, in the text file it could say

sid ,1
sid ,6
sid ,3
sid ,10
sid ,4

but i onlywant it to store

sid ,3
sid ,10
sid ,4

Also, if it isnt too much hassle, does anyone know how i could store the results for the same person horizontally next to thier name ie.

sid (3,10,4)

****A frhr exampe of th input adxpete output if a user called gary completed the quiz 5 times and got scores of 2,4,3,5,7 then one at a time the name gary and the score he got would be written to the text file. but when it gets onto score 5 (4th time gary completes the quiz) then the oldest score of 2 is removed so there would only be 3 scores for gary in the txt file.

Here is a solution using pickle .

Note that pickle is not the safest option or the best for a large dataset, but it is easy. For a webpage SQL with an appropriate front end would be better suited. I am assuming you will only have a few users on the local machine.

To create our pickle object (only need to do this once):

import pickle
name = 'sid'
scores = [10,7,8]

data = {} # dictionary object is well suited for named data
data[name] = scores

with open("out.pickle","wb") as f:
    pickle.dump(data, f) # saves to cwd

Once that is created the following function will add information to the pickled object based on your requirements:

def add_score(name, score, filename="out.pickle"):
    """ """
    # open our 'database'
    with open(filename, "rb") as f:
        data = pickle.load(f)

    # if we already have an entry under this name, add to it.
    # if we don't, create a new one
    if name in data.keys():
        if len(data[name]) > 2: # as we have a maximum length of three
            old_score = data[name].pop(0) # removes the first score
        data[name].append(score)
    else:
        data[name] = [score]

    with open(filename, "wb") as f:
        pickle.dump(data, f)

    return data

An example of how this will look:

>>> d = add_score('sid',11)
>>> d
{'sid': [7, 8, 11]}
>>> d = add_score('sid',14)
>>> d
{'sid': [8, 11, 14]}
>>> 
>>> d = add_score('roger',10)
>>> d
{'sid': [7, 8, 14], 'roger': [10]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM