Having issues sorting values from a text file


#1

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[0])
    write_file.writerow(player_details[1])
    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:

  1. 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?
  2. How do I stop the program from trying to carry on scanning the names and scores?

#2

Question 1:
use sort() on list, so you get

  • player_details.sort()
    before writing it.

Question 2: maybe trying list in list: [[a,b] , [c,d]] instead of your [(a,b), (c,d)].
Maybe he sees player_details[0] as (a,b),(c,d) as one value?

Succes :wink:


#3

I should have made it clearer, the score_filing() function and the variables within it are written after I need to read from the file so I can’t sort the player_details variable as it wouldn’t be defined at that point. Is there a way of splitting and then ordering values from a text file?