【问题标题】:csvreader.fieldnames not recognized as an attribute of a csv reader object in pythoncsvreader.fieldnames 未被识别为 python 中 csv 阅读器对象的属性
【发布时间】:2020-06-16 12:50:04
【问题描述】:

我正在尝试使用 CSV 模块在 Python 中提取 CSV 文件的标题。

CSV 文件非常扁平,看起来像:

这个,那个,另一个

1、2、3

我正在做以下事情:

  1. 读入 CSV 文件并制作 reader 对象
  2. 将阅读器的迭代器推送到下一行以强制它访问第一行至少一次(来自 csv 模块文档:“如果在创建对象时未作为参数传递,则此属性在首次访问时或当从文件中读取第一条记录。”)
  3. .fieldnames 属性分配给变量并打印出来

这里有一段代码来说明:

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

这会导致错误:

AttributeError: '_csv.reader' 对象没有属性 'fieldnames'

这听起来像 .fieldnames 属性不存在,但在 Python 2.6.6 的文档中(我使用的 python 版本相同)

如果能深入了解这个谜团,我将不胜感激。如果有另一种方法来提取标题,那也很棒!

谢谢。

【问题讨论】:

    标签: python csv header


    【解决方案1】:

    如果你真的想使用 csv.reader 而不是 csv.DictReader,你需要做的就是替换

    reader.next() # read next line so header will be accessed
    rfd_header = reader.fieldnames
    

    通过

    rfd_header = reader.next()
    

    【讨论】:

    • 谢谢!这真的很好。我明白为什么 DictReader 可能是一种更好的使用方法,但对于我的应用程序,我需要一个列表。
    • 这对我不起作用。然后我得到'_csv.reader' object has no attribute 'next' (Python 3)
    【解决方案2】:

    尝试使用csv.DictReader 而不是csv.reader。文档也这么说:

    DictReader 对象具有以下公共属性:

    csvreader.fieldnames - 如果在创建对象时未作为参数传递,则在首次访问或从文件中读取第一条记录时初始化此属性。

    http://docs.python.org/library/csv.html

    【讨论】:

    • 你说得对,我一定是误读了文档:P 我会使用 DictReader,但碰巧我需要一个列表。不过感谢您的提示!
    • 嗯“这个属性在首次访问时被初始化”应该是什么意思?对我来说,这听起来像是该类也会在需要的任何时候对字段名进行延迟初始化。
    【解决方案3】:

    如果您需要列表中的结果,您可以采取:

    rfd_header = reader.next()
    

    这应该将第一行(标题/字段)存储到变量“rfd_header”

    然后你可以遍历变量的值并放入一个列表中

    headerList = []
    for item in rfd_header:
        headerList.append(item)
    

    然后就可以打印结果了

    print headerList
    

    【讨论】:

      【解决方案4】:
      >Apropos of 'rfd_header = reader.next' above, I got this error message in IDLE 3.8.3
      >File "<pyshell#2>", line 16, in read_csv_fieldnames
      >   fieldnames = csvreader.next()
      >AttributeError: '_csv.reader' object has no attribute 'next'
      >I fixed it by reading the docco on 'Python.org - CSV File Reading and Writing' 
      >Under the subheading 'Reader Objects' on the last line of page 6 it says;
      >...Usually you should call this as next(reader)
      >1-0 for the Python 'docco'
      

      【讨论】:

      • 虽然这段代码可能会解决问题,包括解释如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。在此链接查看有关如何回答的更多详细信息:stackoverflow.com/help/how-to-answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2022-11-20
      • 2014-12-31
      • 2021-02-07
      • 2018-10-28
      相关资源
      最近更新 更多