Im pretty new to python and am trying to right a small script....

#!/usr/bin/python

import csv
import string

itemlist = []


reader = csv.reader(open("statement.csv", "rb"))
for row in reader:
        item = row[4]
        itemlist.append(item)
        itemlist = list(set(itemlist))

Every time I run it though I get the error :

Traceback (most recent call last):
  File "bank2.py", line 11, in ?
    item = row[4]
IndexError: list index out of range

Can anyone help ??

Dani AI

Generated

, the error means at least one CSV row does not have 5 columns, so row[4] is missing. is right that blank or short rows trigger this, but rather than catching and ignoring every IndexError, validate the data and log or skip only the bad lines. Also, rebuilds of itemlist = list(set(itemlist)) inside the loop are expensive and reorder items. Use a set to track uniqueness as you read.

import csv

items = []
seen = set()

with open("statement.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f, skipinitialspace=True)  # set delimiter=... if not comma
    # If the first row is a header, uncomment the next line:
    # next(reader, None)
    for lineno, row in enumerate(reader, start=1):
        if len(row) <= 4:
            # Optional: print or log short/blank lines to diagnose
            # print(f"Skipping line {lineno}: {row}")
            continue
        item = row[4].strip()
        if item and item not in seen:
            seen.add(item)
            items.append(item)

print(items)

A few quick checks if problems persist:

  • Wrong delimiter: if the file is tab- or semicolon-separated, pass delimiter="\t" or delimiter=";". A wrong delimiter often collapses the whole line into a single column.
  • Extra blank lines: in Python 3, always open CSVs with newline="" (as above). This prevents spurious empty rows.
  • Safer by column name: if the CSV has headers, csv.DictReader lets you use row["YourColumnName"] and avoids magic indexes.
  • Data quality: log the first failing line number and inspect the raw file around it. You may find trailing commas, stray quotes, or embedded newlines inside quoted fields.

The csv reader takes each row in a csv file and converts it to a list so that each column of the row becomes one item in the list. If you have a blank row in the csv file with no data, the corresponding list is empty. If you then try and access a specific element in the row (row[4] in your case), this index will not correspond to an item. Similarly, if there are only 4 columns of data in a row, trying to access the item at row[4] will raise an error since this is the fifth item and a fifth item does not exist.
You need to include a workaround in your code to deal with blank rows, for example:

import csv

reader = csv.reader(open("statement.csv", "rb"))
for row in reader:
    try:
        item = row[4]
    except IndexError:
        pass
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.