Skip to content Skip to sidebar Skip to footer

Python List Index Out Of Range On Return Value Of Split

I'm writing a simple script that is trying to extract the first element from the second column of a .txt input file. import sys if (len(sys.argv) > 1): f = open(sys.argv[1

Solution 1:

I would guess you have a blank line somewhere in your file. If it runs through the data and then generates the exception the blank line will be at the end of your file.

Please insert

print len(line), line

before your

print line[1]

as a check to verify if this is the case.

You can always use this construct to test for blank lines and only process/print non-blank lines:

for line in f:line=line.strip()if line:# process/print line further

Solution 2:

When you are working with list and trying to get value at particular index, it is always safe to see in index is in the range

if len(list_of_elements) > index: 
   print list_of_elements[index]

See:

>>>list_of_elements = [1, 2, 3, 4]>>>len(list_of_elements)
4
>>>list_of_elements[1]
2
>>>list_of_elements[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

Now you have to find out why your list did not contain as many elements as you expected

Answer :

import sys

if (len(sys.argv) > 1):
    f = open(sys.argv[1], "r")
    print"file opened"for line in f:
    line = line.strip().strip('\n')
    # Ensure that you are not working on empty lineif line:
        data = line.split(",") 
    # Ensure that index is not out of rangeiflen(data) > 1: print data[1]

f.close()

Solution 3:

you probably have empty line(s) after your data, I ran your test code without them it worked as expected.

$ python t.py t.txt
file opened
389182.567389182.590389182.611389182.631389182.654

if you don't want to remove them, then simply check for empty lines.

for line in f:
    if line.strip(): # strip will remove allleadingandtrailing whitespace such as'\n'or' 'bydefault    
        line = line.strip("\n ' '")
        line = line.split(",") 
        print line[1]

Solution 4:

It can be useful to catch the exception an print the offending lines

for line in f:
    line = line.strip("\n ' '")
    line = line.split(",") 
    try:
        print line[1]
    except IndexError, e:
        print e
        print"line =", line
        raise# if you don't wish to continue

Post a Comment for "Python List Index Out Of Range On Return Value Of Split"