2017-08-28 83 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

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