-1

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

  • Does this answer your question? [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python) – takendarkk Oct 15 '20 at 14:34
  • Can you give an example of your CSV file? – Alexandre Strapacao G. Vianna Oct 15 '20 at 14:34
  • Your row variable doesn't have a value indexed 1. – zabop Oct 15 '20 at 14:34
  • `with open (file, "a") as f2` should be `with open(file2, "a")`. Also, I'd name `file` as `input_file` and `file2` as `output_file` to be a bir clearer. You also don't need the `delimeter=","` bits; that's the default. Consider using the `csv.DictReader` ... it'll make your life a lot easier, and probably clean up this bug. Bug is hard to pinpoint because we can't see the actual CSV your parsing. – Sam Dolan Oct 15 '20 at 14:36

1 Answers1

0

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]
    ...
Mahrez BenHamad
  • 1,791
  • 1
  • 15
  • 21
  • 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: try: if row: if "spam" in row[0]: writer.writerow([row[1:-1],2]) except Exception as e: print(e) print("done") this code didn't through any error but it simply do anything – Ayaan Mustafa Oct 15 '20 at 14:55