Access CSV data by column name..

M

Michael March

I have seen a few recipes out there that allow for access to DB-API
columns by their name instead of column number.. I was wondering if
anyone knew of any code snippets that allow for the same thing with the
CSV module?

thanks!

<march>
 
L

Larry Bates

The CSV module has a DictReader method that will read each
line into a dictionary with the keys being named by the
column names found on the first line. If the file doesn't have
the first line, it appears you can provide the fieldnames
as a keyword argument to DictReader instead (haven't used this
feature).

<---test file--->
"name","address","city","state","zip","telephone"
"James R. Smith","1234 Vista Lane","Atlanta","GA","30301","4045551212"
"Bill G. Jones","555 Peachtree Lane","Atlanta","GA","30316","4045552323"
"Elanor Allen","7435 Cobb Drive","Atlanta","GA","30332","4045551212"
<--------------->

import csv
fp=open(r'c:\test.txt','r')
inputfile=csv.DictReader(fp)
for record in inputfile:
print record

fp.close()

{'city': 'Atlanta', 'name': 'James R. Smith', 'zip': '30301',
'telephone': '4045551212', 'state': 'GA', 'address': '1234 Vista Lane'}
{'city': 'Atlanta', 'name': 'Bill G. Jones', 'zip': '30316',
'telephone': '4045552323', 'state': 'GA', 'address': '555 Peachtree Lane'}
{'city': 'Atlanta', 'name': 'Elanor Allen', 'zip': '30332',
'telephone': '4045551212', 'state': 'GA', 'address': '7435 Cobb Drive'}

Larry Bates
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top