这是我的代码:
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
原因是什么?
答案 0 :(得分: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)