-2

I'm trying to create a txt file each time someone loses in the game (to save their score)

I succeeded and I now have a list of number which I want to sort, biggest first. Then I will use the 5 first lines each time it will be refreshed.

My txt file (for example):

10
1
5
4
3
2

What I want:

10
5
4
3
2
1

Thanks

#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')
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

1 Answers1

0

You could do this:

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())

Outputs:

10
5
4
3
2
1
Hass786123
  • 666
  • 2
  • 7
  • 16