Python 如何使我的highscore文本文件只有5个highscore

Python 如何使我的highscore文本文件只有5个highscore,python,python-3.x,Python,Python 3.x,我使用了来自的代码,到目前为止它仍然有效,但我不确定如何将高分限制为仅5分,只有最高分数保留在highscore文本文件中。我已经编辑了链接中的代码以适合我的程序: # Winning Code elif U1Score > U2Score: print(username1, "Won") highscores = open("highscores.txt", "r") highscores.close() with open('highscores.t

我使用了来自的代码,到目前为止它仍然有效,但我不确定如何将高分限制为仅5分,只有最高分数保留在highscore文本文件中。我已经编辑了链接中的代码以适合我的程序:

# Winning Code
  elif U1Score > U2Score:
    print(username1, "Won")
    highscores = open("highscores.txt", "r")
    highscores.close()
    with open('highscores.txt', 'w') as f:
      for username1, U1Score in scores:
        f.write('Username: {0}, Score: {1}\n'.format(username1, U1Score))
    highscores.close()
    highscores = open("highscores.txt", "r")
    print(highscores.read())
    highscores.close()
  else:
    print(username2, "Won")
    highscores = open("highscores.txt", "r")
    highscores.close()
    with open('highscores.txt', 'w') as f:
      for username2, U2Score in scores:
        f.write('Username: {0}, Score: {1}\n'.format(username2, U2Score))
    highscores.close()
    highscores = open("highscores.txt", "r")
    print(highscores.read())
    highscores.close()

然而,我仍然不知道如何将分数限制在5个不同的分数,以及如何从最高到最低排序。谢谢,我是新来的:)

简单的解决方案是不打印文件。read()逐行读取文件(因为您使用的分隔符是行),然后只打印5行

大概是这样吧:

f = open("highscores.txt", "r")
highscores_lines = f.read()
for line in highscores_line[:5]:
    print(line)
如果你想按降序排列和打印,你可以使用一些排序算法,按每行的数字排序,然后再打印


排序参考-。

我认为OP想要5个最高分数,但它们没有在highscore文件中排序好,那么我如何对highscore进行排序,以便只打印前5个?我也可以编写排序,但我认为您可以自己处理;)阅读我的新答案,确保你从lineHi Jowan中提取分数,如果你觉得这个答案有用,如果你能接受这个答案,我将不胜感激(:只是想说,它没有很好地集成到我的代码中,我已经尝试过了,但我真的不知道如何排序,因为它显然不是整数。