I want to store the keys of the following CSV file as a list:
"first_name","last_name","email","mobile"
"rahul","sivadas","[email protected]",783434513
"mary","tomy","[email protected]",9839383894
"vijay","govind","[email protected]",9283747393
"vikas","raj","[email protected]",239848392
"ajay","r","[email protected]",982934793
how to get its keys as a list:
['first_name','last_name','email','mobile']
I have tried:
>>> with open('test.csv', 'rb') as f:
header = csv.header(f)
print header
Traceback (most recent call last):
File "<pyshell#4>", line 2, in <module>
header = csv.header(f)
AttributeError: 'module' object has no attribute 'header'
Each row read from the csv file is returned as a list of strings.
The csv
module certainly doesn't have a header
attribute, as the error traceback tells you. I think you probably wanted a csv.DictReader
's fieldnames
attribute:
The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
In use:
>>> import csv
>>> with open('test.csv') as f:
reader = csv.DictReader(f)
print reader.fieldnames
['first_name', 'last_name', 'email', 'mobile']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With