简体   繁体   中英

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. 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:

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]
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM