How To Sort A Text File Numerically?
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
Solution 1:
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")
Post a Comment for "How To Sort A Text File Numerically?"