Search code examples
pythonfileindex-error

How do I sort Python IndexError:List Index out of range when reading and writing with files


I'm working on a game in Python and at the end, scores are written to a file and then the top 5 scores are extracted from the file. This usually works perfectly fine but once I reset the high scores I get an Index error saying "the list index is out of range" Traceback (most recent call last):

File "/home/leo/Documents/Python/infinitest/infinitest.py", line 172, in <module>
    scoreboard()
  File "/home/leo/Documents/Python/infinitest/infinitest.py", line 147, in scoreboard
    print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} : {1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names))
IndexError: list index out of range

How would I fix this

def scoreboard():
    c = add_up1(False)
    d = add_up2(False)
    with open("/home/leo/Documents/Python/infinitest/hi2.txt", "a+") as leaders:
        leaders.write('{},{}\n'.format(c,name1))
        leaders.write('{},{}\n'.format(d,name2))
        line=leaders.readline()
        dic={}
        for line in leaders:
            data = line.split(",")
            dic[int(data[0])] = data[1]
        dic1={}
        for key in sorted(dic.keys()):
            dic1[key]=dic[key]
        scores=list(dic1.keys())
        names=list(dic1.values())
        names =names[::-1]
        scores= scores[::-1]
        print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} :{1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names)) 

In the external file, it is formatted so there is the score, followed by a comma, followed by a username. For example:

100,exampleuser

The add_up functions are fine and just return the total score. I've tried to add placeholder scores to fix the problem, like

1,Placeholder1
2,Placeholder2
3,Placeholder3
4,Placeholder4
5,Placeholder5

and this sometimes work but now is not working again.


Solution

  • After writing to the file its position is at the end - you can see that with leaders.tell(). When you start reading, the for loop exits immediately because there are no more lines and dic remains empty. Later, scores and names are empty so you get an IndexError when you try to access items.

    Before starting to read the file set it's position back to the beginning - if there is a header that you don't want skip the first line:

        ...
        leaders.seek(0)
        #_ = next(leaders)    # skip header
        for line in leaders:
            data = line.split(",")
            dic[int(data[0])] = data[1]