Need help on a top scores function - PYTHON

I’ve written a function to pull results from a text file which includes the name and score of a player. I want to be able to reorder the top 5 results and display them. The formatting of the results file is Name,Score. My code for this is below. However when I run it I get the error “ValueError: not enough values to unpack (expected 2, got 1)”. Could someone please help explain why I keep getting this error?

def top_scores():
    file = open("Results.txt", "r+")
    read_file = csv.reader(file)
    scores = []
    for line in file:
        (name,score) = line.split(",")
#The code fails at the line above
        scores.append((name,score))
    scores.sort(key=lambda tup: tup[1], reverse=True)
    place = ["First", "Second", "Third", "Fourth", "Fifth"]
    for i in range(0,min(len(scores), 5)):
        print(place[i] + ":\n" + scores[i][0] + " - " +  str(scores[i][1]))

The issue might be in your Results.txt file.
One of the lines is probably missing a “,”.

I’ve triple checked the file. It isn’t that. But thx

Let’s have a look at your text file, please.

Unless you want (name,score) to remain as a tuple, you don’t need the parens.

Did you mean, read_file?

Thanks, I did mean read_file I just missed that. However I now get a different error from the line below.
“AttributeError: ‘list’ object has no attribute ‘split’” referring to the line of code below:

   (name, score) = line.split(",")

Here’s a screenshot of the Results.txt file:

image

Lists are already split. Only strings have a .split attribute.

>>> top_scores()
First:
John - 95
Second:
James - 76
Third:
Kye - 76
Fourth:
Julie - 64
Fifth:
Jack - 56
>>> 

I also changed the name of the file to results.csv and imported the csv module so the reader works.


If you use with you don’t have to worry about closing the file, afterward.

    with open('results.csv') as file:
        read_file = csv.reader(file)
        scores = []
        for line in read_file:
            name, score = line
            scores.append((name,score))

Thanks so much, you’ve save me from a lot more hours of head scratching :blush:

1 Like