DictReader and fieldnames

2009-03-19 Thread Ted To
Is it possible to grab the fieldnames that the csv DictReader module
automatically reads from the first line of the input file?

Thanks,
Ted To
--
http://mail.python.org/mailman/listinfo/python-list


Re: DictReader and fieldnames

2009-03-19 Thread skip

Ted Is it possible to grab the fieldnames that the csv DictReader
Ted module automatically reads from the first line of the input file?

Like this, perhaps?

 rdr = csv.DictReader(open(f.csv, rb))
 rdr.fieldnames
['col1', 'col2', 'color']
 rdr.next()
{'color': '3', 'col2': '2', 'col1': '1'}

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: DictReader and fieldnames

2009-03-19 Thread skip

Ted Thanks.  Is there any way to make this work before actually reading
Ted in a row of data?  In version 2.5, I need to first do a rdr.next()
Ted before rdr.fieldnames gives me anything.

If you know the csv file contains column headers this should work:

f = open(f.csv, rb)
names = csv.reader(f).next()
rdr = csv.DictReader(f, fieldnames=names)

Skip
--
http://mail.python.org/mailman/listinfo/python-list