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

2024-03-29 12:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我要将以下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'

Tags: csvnamecom列表email密钥mobilegmail
1条回答
网友
1楼 · 发布于 2024-03-29 12:04:04

正如错误回溯告诉您的,^{} module当然没有header属性。我想你可能想要一个^{}'sfieldnames属性:

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.

使用中:

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


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

相关问题 更多 >