I'm currently working on a challenge that requires me to save high scores to a .txt file. I'm happy with the process of writing the scores to the file, but I'm having some real difficulty working out how to order it in descending order.
I understand that I'm only able to write strings and not integers to a text file, but this leads to me not being able to order the scores as I would like, for example, .sort(reverse=True) would place a 9 higher than 15 on the list.
Is there any way around this issue at all or is this just the nature of writing to a .txt file? Thanks in advance and here is my code:
def high_score():
# open high scores
try:
text_file = open("high_score.txt", "r")
high_scores = text_file.readlines()
except FileNotFoundError:
high_scores = []
# get a new high score
name = input("What is your name? ")
player_score = input("What is your score? ")
entry = (player_score + " - " + name + "\n")
high_scores.append(entry)
high_scores.sort(reverse=True)
high_scores = high_scores[:5]
# write high scores to .txt file
text_file = open("high_score.txt", "w+")
for line in high_scores:
text_file.write(line)