[英]CSV file IndexError: list index out of range
我正在嘗試處理並從 ham/spam 數據集中獲取所有垃圾郵件,並將其寫入另一個 csv 文件。 我的代碼和收到的錯誤在這里:
我的代碼:
import csv
file = "spam.csv"
file2 = "data.csv"
with open(file, "r") as f:
with open(file,"a") as f2:
csvreader1 = csv.reader(f, delimiter=",")
writer = csv.writer(f2, delimiter=",")
for row in csvreader1:
print(len(row))
if "spam" in row[1]:
writer.writerow([row[1],2])
收到錯誤:
Traceback (most recent call last):
File "D:\Email_classifier+ignition\E_mail_classifier\help.py", line 9, in <module>
if "spam" in row[1]:
IndexError: list index out of range
請幫忙
您有兩種解決方案,要么將 if 條件放在 Try/Expect 中,要么在 if 條件之前添加另一個 if:
try:
if "spam" in row[1]:
writer.writerow([row[1],2])
except Exception as e:
print(e)
或者:
if len(row) < 2:
if "spam" in row[1]
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.