-1

I am new to python but have experience with C/sh/java.. My first homework is csv field replacement, if field has specific value

My csv file has 24 columns and has ~ as field seperator. I want to change field 24th with T if it's True My code is like that

import csv
with open ('MyCustomerList.csv', 'r', encoding='utf-8' ) as fi:
    reader = csv.reader (fi, delimiter = '~')
    for row in reader:
        if row[23] == 'True':
            print (row[23])

But it gives an error like that

C:\>c:\Python34\python.exe pyt1.py
    Traceback (most recent call last):
      File "pyt1.py", line 5, in <module>
        if row[23] == 'True':
    IndexError: list index out of range

I could not figured out the issue what is the error ?

2
  • possible duplicate of Python: IndexError: list index out of range Error Commented Jul 27, 2015 at 19:14
  • 1
    Looks like at least one of the rows in the csv file doesn't have 24 items in it. You could wrap the statements where the exception get raised in a try/except and handle the issue as necessary (abort, ignore, substitute, etc) in the except clause. Commented Jul 27, 2015 at 19:46

1 Answer 1

0

The error 'list index out of range' says that you tried to get element after the array ends. I assume that your file really has 24 values, so at first try printing all of them out with index:

i = 0
for row in reader:
    print (i + ' ' + row)
    i += 1

and check if you really get 23rd field (indexing from 0 :).

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

1 Comment

Thanks, csv was corrupted

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.