Question

I'm trying to read through a CSV file that has a couple thousand rows and 3 columns of data. I'm successfully reading through the first and second column, but when I attempt to read through the third column I get an out of range error. In other words:

row=0
rowMax = len(AudioAngle)
while row < rowMax:
    print (AudioAngle[row][0])
    print (AudioAngle[row][1])
    row=row+1

both work and when I add in

print (AudioAngle[row][2])

things only work until the 274th row.
Looking at my CSV file I see this at that line.

00:09.0    0    0
00:09.0    0    0
00:09.0    0    0
00:09.1             <--- line 274
00:09.1    0    0
00:09.1    0    0
00:09.2    0    0

The code has no issue with the empty space in the second column but throws the error in the third column.

Why is this third column throwing an index out of range error at me when I try to read through it?

Was it helpful?

Solution

The parser might just use the space as a separator - thus the space between both first and second, and the second and third column could be seen as separating the first cell from a empty cell in the second column. To get rid of the error, just check for the sublist length! (And please use a for loop...)

for row in AudioAngle:
    print(row[0])
    print(row[1])
    if len(row) >= 3:
       print(row[2])

OTHER TIPS

It makes sense that you will get an index out of range on the 274 row because [1] and [2] don't exist.

If you data may or may not be present, as in the case on line 274, you will need to check to see if it exists before you attempt to use it:

if (AudioAngle[row][0]):
    print (AudioAngle[row][0])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top