如何使用python对文件(高分)排序?

如何使用python对文件(高分)排序?,python,python-3.x,sorting,Python,Python 3.x,Sorting,我目前正在为我的计算机科学课程做一个骰子游戏。我已经到了最后一步,这需要我把我的高分整理成一个文本文件。这就是我目前所拥有的 player1=input("input") ##Temporary inputs (these values are got from the actual code) player1score=int(input("input")) highscore = open("Scores.txt", "r") whowon=("{0}".format(player1sc

我目前正在为我的计算机科学课程做一个骰子游戏。我已经到了最后一步,这需要我把我的高分整理成一个文本文件。这就是我目前所拥有的

player1=input("input") ##Temporary inputs (these values are got from the actual code)
player1score=int(input("input"))


highscore = open("Scores.txt", "r")
whowon=("{0}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()
highscores.sort()
highscores.reverse()


top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]

top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()


基本上,在文档中,它将它们按顺序排序,但它忽略了它拥有的占位符的数量。例如:

8
7
6943734
5
它只会根据排名第一的人进行排序。我也不知道如何修复它。显然,6943734应该在顶部

谢谢。

更换:

highscores.sort()
highscores.reverse()

第一行从字符串中删除换行符,因此可以使用
int()
函数将它们转换为整数,第二行-根据int值按降序排序。 顺便说一句,这部分:

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))
可缩短为:

top = '\n'.join(highscores[0:5])

(在将highscore写入文件之前,您需要在此处添加换行符)。

在highscore.sort()之前使用highscores=[int(x)for x in highscores],因为它被视为字符串。您的代码很难阅读。请使用
with
语句来处理文件,并避免对不同的逻辑部分(例如,打开用于读取和写入的文件)重复使用相同的名称。我在“key=int”中得到了无效语法对不起,我键入错误-参数之间有逗号,而不是点。但是现在,由于某些原因,它没有在高分之间添加新行。请阅读我答案中以“顺便说一句”开头的部分。可能您需要刷新页面。我已经读过了,但是由于某些原因,它没有在.join之前添加“\n”。可能是因为我的python版本吗?它是3.5.1
top = '\n'.join(highscores[0:5])