1

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)
ChrisEzri
  • 13
  • 2

2 Answers2

1

What you need is Natural order sorting... See: https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/

You can simplify the code from the blog to suit your need...

get_sort_keys = lambda k: int(k.split(' ')[0])
high_scores.sort(key=get_sort_keys, reverse=True)
Still-InBeta
  • 383
  • 2
  • 9
  • 2
    Thank you. I used another solution but thanks for introducing me to the idea of natural sorting, much appreciated. – ChrisEzri Mar 29 '18 at 20:53
0

The correct way is to first store a list of pairs (2-tuples) containing each a numerical score and a name, then sort the list by the numerical scores (descending order) and only then convert each pair record to a string and write that to the file.

You code could become:

def high_score():
    # open high score file
    try:
        linenum = 0
        with open("high_score.txt", "r") as text_file:  # ensure proper close
            high_scores = []
            for line in text_file:
                linenum += 1
                score, name = line.strip().split('-', 1)
                high_scores.append((int(score), name))

    except FileNotFoundError:
        high_scores = []
    except ValueError:
        print("Error line", linenum)

    # get a new high score
    name = input("What is your name? ")
    player_score = input("What is your score? ")
    high_scores.append((int(player_score), name))
    high_scores.sort(reverse=True, key=lambda x: x[0])
    high_scores = high_scores[:5]

    # write high scores to .txt file
    with open("high_score.txt", "w+") as high_scores
    for line in high_scores:
        text_file.write(str(line[0] + "-" + line[1])
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Hi, thanks for this, I got it working. I had to convert line[0] and line[1] to strings separately in text_file.write() beforehand though as I was getting a TypeError in that line initially. Thanks very much! – ChrisEzri Mar 29 '18 at 20:52