Matt February 2016

Index error, csv files

Let's say I have a csv file with this in it:

Luke,4
Michael,6

If I run this code, it always returns 'IndexError: list index out of range':

import csv

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        n = row[0]
        print(n)

If I comment out the n = row[0] and change it to print(row), it prints out:

['Luke', '4']
['Michael', '5']
[]

That extra list is causing the problem but I'm not sure how to get rid of it? Any help would be much appreciated!

Answers


Igor February 2016

This is how I handle empty rows when parsing:

import csv

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        if row: # Excluding empty rows here.
            n = row[0]
            print(n)

Post Status

Asked in February 2016
Viewed 2,138 times
Voted 10
Answered 1 times

Search




Leave an answer