IndexError: 列表索引超出范围 - CSV 文件
我的代码出错了,错误信息是 IndexError: list index out of range, at rates[row[0]] = row[1]
:
def change():
# read file into dictionary
with open('exchangeRate.csv', 'r') as in_file:
echRdr = csv.reader(in_file)
for row in echRdr:
rates[row[0]] = row[1]
这个错误是因为我的文件里有空行,可能是我编辑的时候留下的。解决这个问题最简单的方法就是让代码跳过这些空行,我该怎么做呢?
1 个回答
1
在for循环中加一个简单的条件可能就能解决这个问题。
def change():
# read file into dictionary
with open('exchangeRate.csv', 'r') as in_file:
echRdr = csv.reader(in_file)
for row in echRdr:
if len(row) <= 1:
pass
else:
rates[row[0]] = row[1]