我有一个非常简单的.csv格式的数据文件,有一个标题和12列数据。
然而,当我打印出第二列时,数据打印出来确定但我也得到 IndexError:列表索引超出范围。
为什么会这样?
这是我的代码:
with open(filename, 'r',newline='') as f:
reader = csv.reader(f)
#read file row by row
for row in reader:
print(row[1])
Output:
Point
1
2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
File "C:/Users/workspace/Python 3.5/Examples/readFile.py", line 31, in <module>
print(row[1])
IndexError: list index out of range
答案 0 :(得分:1)
您可以使用try/except
块处理错误:
with open(filename, 'r',newline='') as f:
reader = csv.reader(f)
#read file row by row
for row in reader:
try:
print(row[1])
except IndexError, e:
# Do something here to alert you to the error
print(str(e))
print("This row has no 1st index, but here is the row...")
print(row)
...或首先检查索引:
with open(filename, 'r',newline='') as f:
reader = csv.reader(f)
#read file row by row
for row in reader:
if len(row) > 1:
print(row[1])