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)
reader.next()
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 ( )
. , !
.