[英]CSV file IndexError: list index out of range
I am trying to process and get all spam messages from the ham/spam dataset and write it into another csv file.我正在尝试处理并从 ham/spam 数据集中获取所有垃圾邮件,并将其写入另一个 csv 文件。 My code and the error received are here:
我的代码和收到的错误在这里:
My code:我的代码:
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])
Error received:收到错误:
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
Please help请帮忙
You have two solutions, either you put the if condition in Try/Expect or add another if before your if condition:您有两种解决方案,要么将 if 条件放在 Try/Expect 中,要么在 if 条件之前添加另一个 if:
try:
if "spam" in row[1]:
writer.writerow([row[1],2])
except Exception as e:
print(e)
Or:或者:
if len(row) < 2:
if "spam" in row[1]
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.