Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get keys of CSV file as a list?

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'
like image 519
Bamaboy Avatar asked Dec 08 '14 10:12

Bamaboy


People also ask

Does CSV reader return a list?

Each row read from the csv file is returned as a list of strings.


1 Answers

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']
like image 122
jonrsharpe Avatar answered Oct 05 '22 23:10

jonrsharpe