csvreader.fieldnames在python中未被识别为csv reader对象的属性

时间:2010-10-15 20:24:17

标签: python csv header

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

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

  

这,那,其他

     

1,2,3

我正在做以下事情:

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

    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)

    我很感激任何对这个谜团的见解。如果有另一种提取标题的方法也很棒!

    感谢。

4 个答案:

答案 0 :(得分:8)

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

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

通过

rfd_header = reader.next()

答案 1 :(得分:5)

尝试使用csv.DictReader代替csv.reader。文档也说明了这一点:

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

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

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

答案 2 :(得分:0)

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

rfd_header = reader.next()

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

然后你可以迭代变量的值并放入一个列表

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

然后你可以打印结果

print headerList

答案 3 :(得分:0)

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