How do you read text from a file then sort it in decending order?

I have just started to learn Python and I have written the code for a dice game, I have saved the highscores in a text file and at the end, i want to output the top 5 highscores.

i have saved each score in the text file with this structure: name : score

Here is the code ive written:

file = open ("DiceGameScores","r")
for line in file:
    file_line = line.split(": ")
    value = file_line[-1]
    print (value)
    scores = value
print (scores)

mylist = []
mylist.extend (scores)
print (mylist)

mylist.sort(reverse = True)
print (mylist[0:5])


i’ve outputted the scores and the list to check and when i run it i get this:







['4', '6', 'n']
['6', '4', 'n']

46 is the most recent highscore the program is putting each digit as a value of the list and its accepting the new line (n) part of the code

How do i get the top 5 highscores in order and as whole numbers please?


Your two main problems are:

  • Using extend
  • … outside the loop.

extend takes an iterable (the string from the file in that case) and adds all its elements to the list. This is why you get ['4', '6']. Apart from that you get only one number because you do that outside the loop. You need to add the whole number using append and do so inside the loop. You should also convert the scores to ints for proper sorting:

mylist = []
with open("DiceGameScores","r") as file:
    for line in file:
        file_line = line.split(':')
        value = file_line[-1]
        print (value)


Note the use of with to open the file – this is the idiomatic way of handling files in Python. A lot better than using open/close. Embrace it!