2017-08-28 44 views
-3

這是我的代碼:蟒蛇CSV讀取行,但索引超出範圍

with open('example.csv','r',encoding='utf8') as agr: 

    agr_csv = csv.reader(agr, delimiter=',') 
    for line in agr_csv: 
     name = line[0] 
     year = line[2:3] 
     countryname[name].append(year) 

,但我總是得到這樣的錯誤:

Traceback (most recent call last): 
File "quiz_4.py", line 72, in <module> 
name = line[0] 
IndexError: list index out of range 

的原因是什麼?

+1

也許還有空行的CSV –

+0

嘗試'打印(線)'在你的循環,並寫入輸出 – Vladyslav

回答

1

如果有空行,您的代碼將失敗。你可以簡單不過跳過它們:

with open('example.csv','r',encoding='utf8') as agr: 
    agr_csv = csv.reader(agr, delimiter=',') 
    for line in agr_csv: 
     print("Line: >{}<".format(line)) # for debugging 
     if(not line): # check if the line is empty 
      continue # skip 
     name = line[0] 
     year = line[2:3] 
     countryname[name].append(year) 
+0

謝謝!我得到了它的工作:) –