Here is a simple example of load and save. The data is loaded into a list of list, each entry containing the name and score value. On save, the list is sorted by score in descending order, and the top five entries are written to the save file.
def loadscores(file: str) -> []:
scores = []
fi = open("scores.txt", "r")
oldscores = fi.read()
fi.close()
items = oldscores.split('\n')
print(list)
for item in items:
if item != '':
next = item.split('=')
next[1] = int(next[1])
scores.append(next)
print("Loaded:", scores)
return scores
def savescores(file: str, scores: []):
savelist = sorted(scores, key=lambda it: it[1], reverse=True)
try:
fo = open("newscores.txt", "w")
count = 0
for item in savelist:
fo.write(item[0] + '=' + str(item[1]) + '\n')
count += 1
if count == 5:
break
fo.close()
print("Saved:", savelist[:5])
except:
print("Save operation failed")
The text in the score file is in the following format:
Fred=31
Mary=27
John=23
George=17
Brenda=12