How to sort a text file numerically? [duplicate]

两盒软妹~` 提交于 2021-01-29 14:09:06

问题


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


回答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")



来源:https://stackoverflow.com/questions/62284908/how-to-sort-a-text-file-numerically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!