GiudiaLaCarciofa GiudiaLaCarciofa - 2 years ago 102
Python Question

Python strange list behavior

i'm trying to update a csv file using the csv module but i've found some strange behaviour:

consider this code to read a csv

import csv
reader = csv.reader(open('/Users/r2-d2/Desktop/output.csv', 'rb'), delimiter = '\t')

And printing this way

for row in reader:
print row

This code totally works and i get multiple lists one of each represents a row of my cvs

Now consider this code:

for row in reader:
print row[0]

This code does not work for reasons unknown to me. (IndexError: list index out of range) EDIT: row[0] is empty but any other index gives error even if non empty

This code however

for row in reader:
print row[:3]

Works as expected and i get the first 3 entries for each row as a list.

I am definitely missing something.

Answer Source

Some of your rows must be empty.


throws and IndexError when my_list is empty

my_list[:3] will never break, as it will try to give you the slice of data you want, but would return less if my_list is shorter than the last index requested.


for row in reader:
    if row:  # identical to if(len(row))
        print row[0]


I think that you should try to open your file in standard mode, not in binary mode:

reader = csv.reader(open('/Users/r2-d2/Desktop/output.csv', 'r'), delimiter = '\t')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download