CSV文件IndexError:列表索引超出范围

时间:2020-10-15 14:31:48

标签: python csv

我正在尝试从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

请帮助

1 个答案:

答案 0 :(得分:0)

您有两种解决方案,要么将if条件放在“尝试/期望”中,要么在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]
    ...