0

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 ??

Edited by felix001: n/a

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by shibby
0

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
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.