GiudiaLaCarciofa GiudiaLaCarciofa - 6 months ago 8
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

Some of your rows must be empty.

my_list[0]

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.

try:

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

EDIT:

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')
Comments