List index out of range, but list has enough elements

  • Thread starter Costin GamenÈ›
  • Start date
C

Costin GamenÈ›

Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the "print j" statement works, but "print i[0]" returns "IndexError:
list index out of range". Am I missing something?
 
P

Peter Otten

Costin said:
Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the "print j" statement works, but "print i[0]" returns "IndexError:
list index out of range". Am I missing something?

Change

print i[0]

to

print i

You'll see that there are empty rows in your data. You cannot detect these
rows with

for j in i:
print j

because you get zero iterations, i. e. the

print j

statement is never executed for these rows.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top