Read csv, then enumerate

Op.Ivy picture Op.Ivy · Apr 22, 2013 · Viewed 10.9k times · Source

At the moment, I have a list directly in my code and am using enumerate so I can use the list index numbers for the user to select one of the items. Looks like this (just header row included)

fmpList = [['Date', 'ID', 'Plot No', 'Modified', 'Lat', 'Long']......
for item in enumerate(fmpList[]):            
    print "[%d] %s" % item

This works well but I don't want to put the list in the function but rather to read the csv from file. The alternative I used to do this is...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

This also works but I can't seem to combine the 2... read the csv file in, then enumerate to be able to have a selection based on index. Help would be greatly appreciated

EDIT: So now I've got working code as I wanted...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

But the last line is not giving me column 2 only displayed. In fact, I'm after column 0 (the index no) and 2 (the plot name). [0] gives the first column...cool, but any number greater than 1 gives IndexError: ..out of range. Tried every combo but nothing works

Answer

jamylak picture jamylak · Apr 22, 2013

enumerate(...) works on any iterable

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
    next(csvfile, None) # skip header
    plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for i, row in enumerate(plotlist):
        print "[%d] %s" % (i, row)