Python - 索引超出范围错误

时间:2016-01-12 13:26:23

标签: python

这是我最近的代码:

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

这是完整的Traceback错误消息:

 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

1 个答案:

答案 0 :(得分:2)

scores.txt中的部分行没有逗号。你可以检查一下:

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

此代码会忽略没有逗号的行。在计算x = line.split(',')之后放置它。

如果您只想跳过空行,则相同:

if line.strip() == '': #remove whitespace then check if line is empty
    continue