Python Index Out of Range Error

711
3
04-23-2013 08:26 AM
MikeVann
New Contributor
Hi,

I am looping through a csv file using Python to remove header lines, unnecessary columns and trying to replace any blank latitude and longitude coordinate values with a value of (0, 0), these coordinates are in two separate columns. For this replace process I am using a ???for??? loop and the ???replace??? method and am indexing (in the case of the csv file I am working with, the index of the two columns are 36 and 37). However, I keep getting a ???list index out of range??? error message when doing this. Any thoughts to point me in a better direction?

Here's the code:
count = 0
for n in range(6):
    count = count + 1
    line = inFile.readline()

while line:
    count = count + 1
    line = inFile.readline()
    print 'Row', count, 'line info=', line[:72]
    lineList = line.split(',')
    newList = lineList[:72]
    print 'line info =', newList  
    for item in newList[36]: #-> use "if" statement; for column, if name == "LatitudeNAD83" and 
        item.replace("", "0")
    for item in newList[37]:
        item.replace("", "0")
    newLine = ','.join(newList)
    newLine = newLine + '\n'
    formatLine = newLine.replace("/","_")
    outFile.write(formatLine) 


Thanks!

UPDATE: Here's my code in correct format

newList is a list of field names, there should be 72 items in it.
0 Kudos
3 Replies
Luke_Pinner
MVP Regular Contributor
Can you post your script using CODE tags instead of PRE. If you're not sure how to, read this: How to post Python code
0 Kudos
curtvprice
MVP Esteemed Contributor
I keep getting a �??list index out of range�?� error message when doing this.


How many fields are there in the line? If you only have 10, lineList[36] will raise an out of range error.

Here's another shot at this:

# skip 5 rows
skipRows = 5
for n in range(skipRows + 1):
    line = inFile.readline()
row = skipRows + 1
# read and clean up data
while line:
    print 'Row', row, 'line info=', line[:72]
    # clean line and split into list
    lineList = [f.strip().replace("/","_") for f in line.split(',')]
    print 'line info =', lineList
    latidx,lonidx = 36, 37 # lat and long are in field 36 and 37
    if len(lineList) > lonidx: 
        raise Exception, "line {0} too short".format(row)
    for k in latidx, lonidx:
        if lineList == "":
            lineList = 0
    outFile.write(','.join(newList) + "\n") 
    line = inFile.readline()
    row += 1   
0 Kudos
curtvprice
MVP Esteemed Contributor
newList is a list of field names, there should be 72 items in it


Apparently not, if you're getting that error. I suggest using a try-except block to find which line is causing the problem (see my code for an example).
0 Kudos