首页 > 解决方案 > 排序txt文件以创建排行榜

问题描述

每次有人在游戏中失败时,我都会尝试创建一个 txt 文件(以保存他们的分数)

我成功了,我现在有一个我想要排序的数字列表,最大的在前。然后每次刷新时我都会使用前 5 行。

我的 txt 文件(例如):

10
1
5
4
3
2

我想要的是:

10
5
4
3
2
1

谢谢

#Saving the score    
Scorefile = open('Scoreboard.txt','a')    
Scorefile.write(str(score))    
Scorefile.write('\n')    
Scorefile.close()    

#Sorting the file   
Scorefile = open('Scoreboard.txt','a')

标签: pythonsortingtextnumbers

解决方案


你可以这样做:

file = open("Scoreboard.txt","r")
lines = list(file) #create a list of strings
file.close() #don't forget to close our files when we're done. It's good practice.
modified_lines = [] #empty list to put our modified lines in (extracted number, original line)
for line in lines: #iterate over each line
    if line.strip(): #if there's anything there after we strip away whitespace
        score = line.split(' ')[0] #split our text on every space and take the first item
        score = int(score) #convert the string of our score into a number
        modified_lines.append([score, line]) #add our modified line to modified_lines

#sort our list that now has the thing we want to sort based on is first
sorted_modified_lines = sorted(modified_lines, reverse = True) 

#take only the string (not the number we added before) and print it without the trailing newline.
for line in sorted_modified_lines:
    print(line[1].strip())

输出:

10
5
4
3
2
1

推荐阅读