I’ve written a game that saves the 2 player’s scores when the game ends. However I am trying to add an option to the start menu that will allow me to present the top 5 scores. I’ve used csv to format the results I output to the text file, and am successful using the .split(",") function for each line but can’t find a way to order the scores.
Saving to the file
This is successful
def score_filing(): file = open("Results.txt", "a") write_file = csv.writer(file) player_details = [(p1_name, p1_score),(p2_name, p2_score)] write_file.writerow(player_details) write_file.writerow(player_details) file.close() score_filing()
Trying to read the file
This is semi-successful but I do not know how to stop the program from it keep scanning the file for more data. See below.
from time import sleep #I've only used sleep so I could slow down the output to see errors import csv file = open("Results.txt", "r+") for line in file: line_split = line.split(",") (name, score) = line_split print(name, score) sleep(1)
I do get an error when it gets to the end of the text file however:
ValueError: not enough values to unpack (expected 2, got 1)
Which I believe to be the program not stopping when it gets to the end of the values in the text file.
So I have 2 questions:
- The main question I have is how do I order the scores highest to lowest then print them with the appropriate names of the players?
- How do I stop the program from trying to carry on scanning the names and scores?