2016-01-12 49 views
-8

这是我最近的代码: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 (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

一些scores.txt没有逗号你行(“”)在他们。 另外,使用更好的标题。 – Sildar

+2

这真的是你可以提出的最具描述性的标题吗? – David

+1

它说错误。 “列表索引超出范围”。您在某些行中没有逗号或缺少数据。 – Chris

回答

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 
+0

谢谢大家,它终于奏效了 –