Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

  • The csv module's DictReader object has a public attribute called fieldnames (as of Python 2.6 and above). https://docs.python.org/3.4/library/csv.html#csv.csvreader.fieldnames

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    dict_reader = csv.DictReader(f)

    #get header fieldnames from DictReader and store in list
    headers = dict_reader.fieldnames

    #sample file reading logic
    for line in dict_reader:
        print(line[headers[0]])
        

In the above, dict_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyColumn1', 'MyColumn2', 'MyColumn3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()
    
    dict_reader = csv.DictReader(f)
    headers = dict_reader.fieldnames

    #sample file reading logic
    for line in dict_reader:
        print(line[headers[0]])
Answer from user3194712 on Stack Overflow
Top answer
1 of 10
155

Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

  • The csv module's DictReader object has a public attribute called fieldnames (as of Python 2.6 and above). https://docs.python.org/3.4/library/csv.html#csv.csvreader.fieldnames

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    dict_reader = csv.DictReader(f)

    #get header fieldnames from DictReader and store in list
    headers = dict_reader.fieldnames

    #sample file reading logic
    for line in dict_reader:
        print(line[headers[0]])
        

In the above, dict_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyColumn1', 'MyColumn2', 'MyColumn3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()
    
    dict_reader = csv.DictReader(f)
    headers = dict_reader.fieldnames

    #sample file reading logic
    for line in dict_reader:
        print(line[headers[0]])
2 of 10
85

You can read the header by using the next() function which return the next row of the reader’s iterable object as a list. then you can add the content of the file to a list.

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = reader.next()
    rest = list(reader)

Now i has the column's names as a list.

print i
>>>['id', 'name', 'age', 'sex']

Also note that reader.next() does not work in python 3. Instead use the the inbuilt next() to get the first line of the csv immediately after reading like so:

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = next(reader)

    print(i)
    >>>['id', 'name', 'age', 'sex']
🌐
Medium
medium.com › @daniel.gm78 › get-headers-from-csv-file-python-1d391128c2b7
Get Headers from CSV file(Python) | by Daniel Gomez | Medium
July 15, 2025 - For example, given this CSV · file id, name 1, daniel 2, patrick It will be read as: read as a dict {"id": "1", "name": "daniel"} {"id": "2", "name": "patrick"} ... The headers can be extracted directly from the DictReader object’s fieldnames attribute, without needing to read any rows.
Discussions

python - How to write header row with csv.DictWriter? - Stack Overflow
Put another way: The Fieldnames ... because Python dicts are inherently unordered. Below is an example of how you'd write the header and data to a file. Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement · Copywith open(infile,'rb') as fin: dr = csv.DictReader(fin, ... More on stackoverflow.com
🌐 stackoverflow.com
Python csv DictReader with optional header - Stack Overflow
because DictReader is not skipping the header row, when it exists. ... You may be able to use a csv.Sniffer here. More on stackoverflow.com
🌐 stackoverflow.com
python csv headers - Stack Overflow
I have a set of csv headers that I am trying to match with uploads. It's not really working. Not all headers are required -- I just have to match what's in the file. reader = csv.DictReader(open( More on stackoverflow.com
🌐 stackoverflow.com
November 7, 2011
How Can I Check if a CSV File has Headers
The csv module in the standard library already has the capability to determine if a given csv file has headers or not. https://stackoverflow.com/questions/40193388/how-to-check-if-a-csv-has-a-header-using-python/40193509 More on reddit.com
🌐 r/learnpython
12
3
May 12, 2021
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
Note that unlike the DictReader class, the fieldnames parameter of the DictWriter class is not optional. If the argument passed to fieldnames is an iterator, it will be coerced to a list. ... import csv with open('names.csv', 'w', newline='') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
🌐
Python Morsels
pythonmorsels.com › csv-reading
Reading a CSV file in Python - Python Morsels
January 23, 2023 - Python's csv module includes helpers for reading CSV files. You can use csv.reader to get back lists representing each row in your file. Or if you prefer to rely on the headers in your file, you can use csv.DictReader to get dictionaries representing each of those rows.
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-csv › writing › writing › dictwriter-with-writeheader
Read and Write CSV in Python | Learn Python | Vertabelo Academy
You have to add it manually by invoking the writeheader() method: data_to_save = [ {'Author':'John Smith', 'Title':'Keep holding on', 'Pages':'326'}, {'Author':'Erica Coleman', 'Title':'The beauty is the beast', 'Pages':'274'} ] with ...
Top answer
1 of 4
179

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)
2 of 4
31

A few options:

(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

(2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

dw.writer.writerow(dw.fieldnames)

(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

Writing data:

w.writerow([d[k] for k in fieldnames])

or

w.writerow([d.get(k, restval) for k in fieldnames])

Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

============

>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\csv.py", line 144, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\python26\lib\csv.py", line 141, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>
Top answer
1 of 4
3

You may be able to use a csv.Sniffer here.

The has_header method peeks at the data and uses heuristics to determine whether a header is present (refer to the doc for the exact logic).

Note that in the example data shown in the question, the sniffer heuristic would incorrectly consider both headerless and headerful to have a header. That's probably a consequence of your sample data having only a single row, if I add a second numeric row 4,5,6 in the input data then the Sniffer.has_header method works as expected.

A basic implementation which assumes csvfile is seekable could look like this:

def print_data_rows(csvfile):
    reader = csv.DictReader(csvfile, fieldnames=FIELDNAMES)
    sniffer = csv.Sniffer()
    sample = csvfile.read(1024)
    csvfile.seek(0)
    if sniffer.has_header(sample):
        next(reader)
    for row in reader:
        print(row)

It's easy to adapt if your stream isn't seekable, just buffer the first line.

2 of 4
2

You can implement the custom behavior by overriding csv.DictReader.__next__ such that it would read another row if the first row is the same as the given field names:

class HeaderOptionalDictReader(csv.DictReader):
    def __init__(self, *args, fieldnames=None, **kwargs):
        super().__init__(*args, fieldnames=fieldnames, **kwargs)
        self.skip_header = fieldnames is not None

    def __next__(self):
        row =  super().__next__()
        if self.skip_header and list(row.values()) == self.fieldnames:
            row = super().__next__()
        self.skip_header = False
        return row

Demo: https://ideone.com/eYbiZg

Find elsewhere
🌐
Runebook.dev
runebook.dev › en › docs › python › library › csv › csv.DictReader.fieldnames
Python CSV Headers: The Complete Guide to csv.DictReader.fieldnames
A common practice is to skip the header line first, then use DictReader. import csv import io # CSV data has no header row csv_data_no_header = "Alice,30,Tokyo\nBob,25,Osaka" file = io.StringIO(csv_data_no_header) # Define the names you want to use CUSTOM_HEADERS = ['Person_Name', 'Years_Old', 'Location'] # Pass the custom list to fieldnames reader = csv.DictReader(file, fieldnames=CUSTOM_HEADERS) # The fieldnames attribute is immediately set!
🌐
CodeRivers
coderivers.org › blog › python-csv-dictreader
Python `csv.DictReader`: A Comprehensive Guide - CodeRivers
February 22, 2026 - The csv.DictReader class in Python's csv module is designed to read rows of a CSV file as dictionaries. Each dictionary represents a row in the CSV file, where the keys are the column headers from the first row of the CSV file (the header row), and the values are the corresponding cell values ...
🌐
TECH CHAMPION
tech-champion.com › tech champion › programming › python programming › handling optional headers with python csv dictreader
Python CSV DictReader: Handling Optional Headers Effectively
October 17, 2025 - When working with CSV files in Python, the csv.DictReader class is invaluable for reading data into dictionaries, where each row is represented as a dictionary with keys derived from the header row. However, a common challenge arises when the CSV file may or may not contain a header row.
🌐
LearnPython.com
learnpython.com › blog › guide-to-the-python-csv-module
A Guide to the Python csv Module | LearnPython.com
January 23, 2023 - See how the header labels became the keys to each row’s dictionary? The csv.DictReader assumes that the first row is the header – a very safe assumption – and uses its labels to create the dictionaries.
🌐
Real Python
realpython.com › videos › reading-csvs-pythons-csv-module
Reading CSVs With Python's "csv" Module (Video) – Real Python
@Kim If you don’t explicitly provide a list of field names for your records, then DictReader will assume the first line in the CSV file is the header.
Published   March 1, 2019
🌐
w3reference
w3reference.com › blog › python-writing-a-csv-to-a-list-of-dictionaries-with-headers-as-keys-and-rows-as-values
How to Convert CSV to List of Dictionaries in Python Using csv.DictReader (Headers as Keys) — w3reference.com
The csv.DictReader class is part of Python’s built-in csv module. It reads CSV files and maps each row to a dictionary, where: Keys are the CSV headers (the first row, by default).
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-3-dictreader-e4814ce2e44
Using Python CSV #3 — DictReader
December 22, 2022 - In this article, we’ll look at csv.DictReader and in the next article csv.DictWriter. First, let’s create a csv. If you read my Using Python CSV #2 — Basic Writing, then you know that we can create a csv file with csv.writer. Let’s create a hypothetical csv that contains the name, age, and account size of various clients. headers ...
🌐
Imperial College London
python.pages.doc.ic.ac.uk › java › lessons › java › 10-files › 09-csvreaddict.html
Python for Java Programmers > Reading CSV files into a dict | Department of Computing | Imperial College London
To make life easier, you can also read in the CSV files into a dict, using a csv.DictReader object. You can then access elements using the column names as keys (from the first row). There is also no need to explicitly read the header row (this is automatically done by csv.DictReader).
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-column-names-from-csv-using-python
Get column names from CSV using Python - GeeksforGeeks
June 30, 2025 - import csv with open('path_for_data.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') header = next(csv_reader) print("List of column names:", header) ... This method reads the CSV as a dictionary, allowing you to extract the ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-headers-and-types-when-processing-csv-data-in-python-417808
How to handle headers and types when processing CSV data in Python | LabEx
By default, the csv.reader() function in Python treats all data as strings. This means that if your CSV file contains numerical or date/time values, they will be read as strings. To handle this, you can use the csv.DictReader class, which automatically infers the data types based on the values in the CSV file.
🌐
Python Pool
pythonpool.com › home › blog › csv dicteader doesn’t have to be hard
CSV Dicteader Doesn't Have To Be Hard - Python Pool
December 18, 2021 - This module is inbuilt in python libraries and hence requires no installation. We need to import it while handling CSV files. To do that, we will use the following commands. ... This module has several classes and functions that provide different access for reading & writing data and making changes in the files. Some of the classes are CSV.reader, CSV.writer, CSV.DictReader, CSV.DictWriter, CSV.excel e.t.c..
🌐
DEV Community
dev.to › bowmanjd › flexible-csv-handling-in-python-with-dictreader-and-dictwriter-3hae
Flexible CSV Handling in Python with DictReader and DictWriter - DEV Community
February 9, 2026 - With CSV handling in Python, however, we do not need to load the contents of the file into memory. Instead, we pass the file handle (infile in our example above) to a csv.DictReader.