You can use dict to save your record and simply write it to a file:
def store_highscore_in_file(dictionary, fn = "./high.txt", top_n=0): """Store the dict into a file, only store top_n highest values.""" with open(fn,"w") as f: for idx,(name,pts) in enumerate(sorted(dictionary.items(), key= lambda x:-x[1])): f.write(f"{name}:{pts}\n") if top_n and idx == top_n-1: break def load_highscore_from_file(fn = "./high.txt"): """Retrieve dict from file""" hs = {} try: with open(fn,"r") as f: for line in f: name,_,points = line.partition(":") if name and points: hs[name]=int(points) except FileNotFoundError: return {} return hs
Usage :
# file does not exist k = load_highscore_from_file() print(k) # add some highscores to dict k["p"]=10 k["a"]=110 k["k"]=1110 k["l"]=1022 print(k) # store file, only top 3 store_highscore_in_file(k, top_n=3) # load back into new dict kk = load_highscore_from_file() print(kk)
Output:
{} # no file {'p': 10, 'a': 110, 'k': 1110, 'l': 1022} # before storing top 3 {'k': 1110, 'l': 1022, 'a': 110} # after loading the top 3 file again
source share