gpt4 book ai didi

python - 如何获取 CSV 文件的键作为列表?

转载 作者:行者123 更新时间:2023-11-28 21:53:00 25 4
gpt4 key购买 nike

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

最佳答案

csv module正如错误回溯告诉您的那样,肯定没有 header 属性。我想你可能想要一个 csv.DictReader's fieldnames 属性:

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

关于python - 如何获取 CSV 文件的键作为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com