Reputation: 2173
I am reading a csv file using the csv.DictReader class. I read on the python documentation that class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
I tried to get the first row of my csv file using the keys() method of dictionaries:
my_reader = csv.DictReader(src)
print(my_reader.keys())
Doing this, I get the following error:
print(my_reader.keys())
AttributeError: 'DictReader' object has no attribute 'keys'
Why?
Upvotes: 3
Views: 2293
Reputation: 879749
The fieldnames are stored in the attribute fieldnames
:
my_reader = csv.DictReader(src)
print(my_reader.fieldnames)
keys
is a dict method. my_reader
is not a dict. However, it is an iterator that yields dicts, so you could also do this:
for row in my_reader:
print(row.keys())
Upvotes: 2