如何获取CSV文件的密钥作为列表?

时间:2014-12-08 10:52:17

标签: python python-2.7

我想将以下CSV文件的密钥存储为列表:

"first_name","last_name","email","mobile"
"rahul","sivadas","rahul@gmail.com",783434513
"mary","tomy","mary@gmail.com",9839383894
"vijay","govind","vijay@gmail.com",9283747393
"vikas","raj","vikas@gmail.com",239848392
"ajay","r","ajay@gmail.com",982934793

如何将其密钥作为列表:

['first_name','last_name','email','mobile']

我试过了:

>>> 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'

1 个答案:

答案 0 :(得分:5)

csv module肯定没有header属性,因为错误跟踪会告诉您。我想你可能想要一个csv.DictReader's fieldnames属性:

  

fieldnames 参数是序列,其元素按顺序与输入数据的字段相关联。如果省略 fieldnames 参数, csvfile 第一行中的值将用作字段名。

使用中:

>>> import csv
>>> with open('test.csv') as f:
    reader = csv.DictReader(f)
    print reader.fieldnames


['first_name', 'last_name', 'email', 'mobile']