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:
.fieldnames
attribute to a variable and print ithere 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.
If you truly want to use csv.reader instead of csv.DictReader, all you need to do is replace
reader.next() # read next line so header will be accessed
rfd_header = reader.fieldnames
by
rfd_header = reader.next()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With