0
我已在python腳本寫爲:Python的IndexError:列表超出範圍的錯誤
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]爲讀者行)' - 如果你有空行,你可以提供保護,例如'「」。加入(行[0]中讀取行,如果行)' – AChampion
只是打印'for'循環內'row'值,我想在輸入文件中的空行,其中的一些是存在的。輸入csv中的問題,而不是python代碼。 –