0

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?

4
  • I'm seeing four columns in your CSV file, and it appears that the third one is the first column with a blank - that seems consistent with your IndexError. Is the first column in AudioAngle not the row numbers? Commented Aug 21, 2013 at 17:13
  • sorry for the confusion, the first column you saw was actually row numbers added in by myself - edited that to make it clearer Commented Aug 21, 2013 at 17:16
  • What's the question and where is the code? Commented Aug 21, 2013 at 17:20
  • tried to make things clearer Brent - I'm getting an out of range error and I don't know why. my code runs perfectly fine for the first two columns and the second column has identical empty space compared to the third column Commented Aug 21, 2013 at 17:29

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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])

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.