2016-01-12 48 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

謝謝大家,它終於奏效了 –