Get the first csv line using a dictionary

I am reading a csv file using the csv.DictReader class. I read in the python documentation that class csv.DictReader (csvfile, fieldnames = None, restkey = None, restval = None, dialect = 'excel', * args, ** kwds)

If fieldnames is omitted, the values ​​in the first line of csvfile will be used as field names.

I tried to get the first line of my csv file using the dictionary method :()

my_reader = csv.DictReader(src) print(my_reader.keys()) 

By doing this, I get the following error:

  print(my_reader.keys()) AttributeError: 'DictReader' object has no attribute 'keys' 

Why?

+4
source share
1 answer

Field names are stored in the fieldnames attribute:

 my_reader = csv.DictReader(src) print(my_reader.fieldnames) 

keys is a dict method. my_reader not a dict. However, this is an iterator that gives dicts, so you can also do this:

 for row in my_reader: print(row.keys()) 
+3
source

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


All Articles