csvreader.fieldnames 不被识别为 python 中 csv reader 对象的属性
我正在尝试使用 CSV 模块在 Python 中提取 CSV 文件的标头。
CSV 文件非常扁平,看起来像:
这个、那个、其他
1,2,3
我正在执行以下操作:
- 读取 CSV 文件并让读取器对象
- 将读取器的迭代器推送到下一行,以强制它访问第一行至少一次(来自 csv 模块文档:“如果在创建对象时未作为参数传递,则在首次访问或从文件中读取第一条记录时初始化此属性。”
- ) /code> 属性到变量并打印它
这里是一个代码片段来说明:
datafile = open(fname, "rb")
reader = csv.reader(datafile) #use csv module to parse in the header
reader.next() # read next line so header will be accessed
rfd_header = reader.fieldnames
print "header:\n"
print rfd_header
这会导致错误:
属性错误:“_csv.reader”对象没有属性“fieldnames”
听起来好像 .fieldnames
属性不存在,但在 Python 2.6.6 的文档中(我是同一版本的 python使用)
我将不胜感激任何对这个谜团的深入了解。如果有一种替代方法来提取标头,那就太棒了!
谢谢。
I am trying to extract the header of a CSV file in Python by using the CSV module.
The CSV file is quite flat, and looks something like:
This, That, The Other
1, 2, 3
I am doing the following:
- Read in the CSV file and make the reader object
- push the reader's iterator to the next line to force it to access the first line at least once (from the csv module documentation: "If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.")
- assigning the
.fieldnames
attribute to a variable and print it
here is a snippet of code to illustrate:
datafile = open(fname, "rb")
reader = csv.reader(datafile) #use csv module to parse in the header
reader.next() # read next line so header will be accessed
rfd_header = reader.fieldnames
print "header:\n"
print rfd_header
This results in an error:
AttributeError: '_csv.reader' object has no attribute 'fieldnames'
Which sounds like the .fieldnames
attribute isn't there, but is in the documentation of Python 2.6.6 (same version of python I am using)
I would appreciate any insight into this mystery. If there is an alternative method to extract the header that would be awesome too!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你真的想使用 csv.reader 而不是 csv.DictReader,你需要做的就是替换
为
If you truly want to use csv.reader instead of csv.DictReader, all you need to do is replace
by
尝试使用
csv.DictReader
而不是csv.reader
。文档也这么说:DictReader 对象具有以下公共属性:
csvreader.fieldnames - 如果在创建对象时未作为参数传递,则此属性将在首次访问或第一次访问时初始化记录是从文件中读取的。
http://docs.python.org/library/ csv.html
Try
csv.DictReader
instead ofcsv.reader
. The documentation says it too:DictReader objects have the following public attribute:
csvreader.fieldnames - If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.
http://docs.python.org/library/csv.html
如果您需要列表中的结果,您可以采取:
这应该将第一行(标题/字段)存储到变量“rfd_header”
然后您可以迭代变量的值并将其放入列表中
然后您可以打印结果
If you need the result in a list, you could take:
This should store the first row (header/fields) to the variable "rfd_header"
Then you could iterate over the variable's values and put into a list
Then you can print the result