0

I am trying to sort a text file in numerical order, from largest at the top of the file, to lowest at the bottom of the file. Each line in the file only contains one number. I want to know how I can sort the text file every time run the code so that the numbers are always sorted. This is then used so I can then make a leaderboard.

    savefile.write("\n")
    savefile.write(User1)
    savefile.write(" Got a total score of ")
    savefile.write(Total1)
    savefile.close()
    savefile = open("Winnersnum.txt","a")
    savefile.write("\n")
    savefile.write(Total1)
    savefile.close()

All the numbers are saved in winnersnum.txt and if anyone could tell me how to sort it that would be great. (I know I can sort it using variables and reading but I don't want to have to make a bunch of lines to read with a bunch of variables)

Here is an example of the Winnersnum text file: Picture of file

D3monalex
  • 1
  • 1
  • Please add an example of your Winnersum.txt file, thanks! – EnriqueBet Jun 09 '20 at 14:28
  • Typically, it's better to paste a short stretch of data like that right into the question, rather than linking to a screenshot. It saves the people helping you some alt-tabbing and typing. – Mike Jun 09 '20 at 14:45

1 Answers1

0

You can store all the values in a list, sort the list, and write them out, as such:

with open("winnersum.txt", "r") as txt:
    file = txt.read()

scores = file.split('\n') #converts to list
scores = [int(x) for x in scores] #converts strings to integers
scores.sort(reverse=True) # sorts results

with open("winnersum.txt", "w") as txt:
    for i in scores:
        txt.write(f"{i}\n")

Ahmet
  • 434
  • 4
  • 13