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","teleph one"
"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:\te st.txt','r')
inputfile=csv.D ictReader(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
Michael March wrote:
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>