排序txt文件以创建页首横幅

时间:2019-05-15 17:05:51

标签: python sorting text numbers

每次有人在游戏中失败时,我都试图创建一个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')

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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