Csvreader.fieldnames not recognized as attribute of csv read object in python

I am trying to extract the header of a CSV file in Python using the CSV module.

The CSV file is pretty flat and looks something like this:

This, That, The Other

1, 2, 3

I do the following:

  • Read in the CSV file and create a reader object
  • click the reader iterator on the next line to force it to access the first line at least once (from the csv module documentation: "If this was not passed as a parameter when creating the object, this attribute is initialized when it is first accessed or when the first record is read from the file . ")
  • assigning a variable to a .fieldnamesvariable and printing 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 will result in an error:

AttributeError: '_csv.reader' 'fieldnames'

, .fieldnames , Python 2.6.6 ( )

. , !

.

+3
3

csv.reader csv.DictReader, , ,

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

rfd_header = reader.next()
+7

csv.DictReader csv.reader. :

DictReader :

csvreader.fieldnames - , .

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

+4

If you need the result in the list, you can take:

rfd_header = reader.next()

This should store the first line (header / fields) in the variable "rfd_header"

Then you can iterate over the values ​​of the variables and put them in a list

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

Then you can print the result

print headerList
0
source

Source: https://habr.com/ru/post/1769808/


All Articles