0

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?

2
  • Probably because you have an empty line in the file (perhaps at the end). You could have just used a generator expression: ','.join(row[0] for row in reader) - if you have empty lines you could provide a guard, e.g. ','.join(row[0] for row in reader if row) Commented Aug 25, 2017 at 4:03
  • just print row value inside for loop, I think some where in input file empty row is present. Problem in input csv, not in python code. Commented Aug 25, 2017 at 4:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.