rrene
rrene

Reputation: 323

Python IndexError: list out of range error

I have the python script written as :

import csv
with open ("ann.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    collected = []
    for row in reader:
        collected.append(row[0])
    print (",".join(collected))

ann.csv file as :

colums_header
7432
7849
7844
7108
8712
7833
7842
8723
7895
8719
9899
7352
7515
7252
8906
continued

When I try to run the python script it gives error :

Traceback (most recent call last):
  File "columnTorow.py", line 6, in <module>
    collected.append(row[0])
IndexError: list index out of range

Why am I getting the out of range exception?

Upvotes: 0

Views: 69

Answers (1)

Phuong Nguyen
Phuong Nguyen

Reputation: 306

The reason is you have an empty line somewhere in the middle of the file or at the end of the file. You should add a condition checking before adding the item to your list like this:

for row in reader:
    if row:
        collected.append(row[0])

Hope this helps.

Upvotes: 1

Related Questions