我将python脚本写成:
import csv
with open ("ann.csv", "r") as csvfile:
reader = csv.reader(csvfile)
collected = []
for row in reader:
collected.append(row[0])
print (",".join(collected))
ann.csv文件为:
colums_header
7432
7849
7844
7108
8712
7833
7842
8723
7895
8719
9899
7352
7515
7252
8906
continued
当我尝试运行python脚本时,它会出错:
Traceback (most recent call last):
File "columnTorow.py", line 6, in <module>
collected.append(row[0])
IndexError: list index out of range
为什么我会超出范围异常?
答案 0 :(得分:1)
原因是文件中间或文件末尾的某处有一个空行。您应该在将项目添加到列表之前添加条件检查,如下所示:
for row in reader:
if row:
collected.append(row[0])
希望这有帮助。