Python – index out of range error

Question:

This is my most recent code:

highest = {}
def reader():
    myfile = open("scores.txt","r")
    pre = myfile.readlines()

    print(pre)


    for line in pre :
       print(line)
       x = line.split(",")

       a = x[0]

       b = x[1]

       c = len(b)-1
       b = b[0:c]

       highest[a] = b

And this is the Traceback error message in full:

 Traceback (most recent call last):
        File "C:/Python34/my boto snaky/snaky.py", line 568, in gameLoop
        reader()
        File "C:/Python34/my boto snaky/snaky.py", line 531, in reader
        b = x[1]
        IndexError: list index out of range
Asked By: Anihs Emma

||

Answers:

Some of your lines in scores.txt don’t have a comma. You can check for those :

if len(x) == 1 : #there is no comma
    continue #ignore line and go to the next one

This code would ignore the lines without a comma. Place it just after computing x = line.split(‘,’) .

Same if you just want to skip empty lines :

if line.strip() == '': #remove whitespace then check if line is empty
    continue
Answered By: Sildar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.