[英]how to write to the top line of a text file in python
我正在嘗試為我制作的游戲創建排行榜。 我試圖將最近的高分寫入文本文件的頂行,高於其他行,我該怎么辦?
這是我的代碼:
s = open("highscore.txt", 'r')
scores = s.read()
scores = int(scores)
if score > (scores):
highscore = score
print("NEW HIGH SCORE")
s = open("highscore.txt", 'a')
s.write(str(highscore))
s.write("\n")
s.close()
s = open("highscore.txt", 'r')
scores = s.read()
scores = int(scores)
s.close()
我認為最直接的方法是打開第二個高分文件,您首先在其中寫入新分數,然后是舊高分文件的內容。
然后刪除舊文件並重命名新文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.