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
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
If the argument passed to fieldnames is an iterator, it will be coerced to a list. Changed in version 3.6: Returned rows are now of type OrderedDict. Changed in version 3.8: Returned rows are now of type dict. ... >>> import csv >>> with open('names.csv', newline='') as csvfile: ... reader = csv.DictReader(csvfile) ...
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-3-dictreader-e4814ce2e44
Using Python CSV #3 — DictReader
December 22, 2022 - Fieldnames are either explicitly specified or are the first row of the csv. Our fieldnames should be the first row (the header): ‘name’, ‘age’, and ‘account’. These should map to the name, age, and account size of each person.
Discussions

python - Reading column names alone in a csv file - Stack Overflow
Interesting - for what it's worth, a hello world CSV reader in Python 3.7 gives proper fieldnames for me 2019-09-12T18:29:52.497Z+00:00 ... The DictReader.fieldnames solution is very efficient. More efficient than other methods mentioned in this post, according to my timing. Thanks! 2019-12-19T16:47:43.26Z+00:00 ... Save this answer. ... Show activity on this post. You can read the header by using the next() function which return the next row of the reader’s iterable object as a list... More on stackoverflow.com
🌐 stackoverflow.com
csv.DictReader when one of my fields is a list
Your problem is due to badly-formed CSV data. A field with commas in it is supposed to have surrounding "..." quotes. Putting those in you get something closer to what you want. Another difficulty is the spaces you have in your data file between the header and data fields. Try using this test data file test.csv: item,num_ordered,people apple,4,"['Janet', 'Sam']" grape,1,"['Stu', 'Jenny']" and running this test code: import csv with open("test.csv") as fd: reader = csv.DictReader(fd) for line in reader: print(line) Then you get this printed: {'item': 'apple', 'num_ordered': '4', 'people': "['Janet', 'Sam']"} {'item': 'grape', 'num_ordered': '1', 'people': "['Stu', 'Jenny']"} More on reddit.com
🌐 r/learnpython
3
1
August 29, 2023
python - Replace fieldnames when using DictReader - Stack Overflow
I have a test.csv file: foo,bar,foobar,barfoo 1,2,3,4 5,6,7,8 9,10,11,12 And the following CSV parser: #!/usr/bin/env python # -*- coding: utf-8 -*- import csv import json f = open ( 'test.csv... More on stackoverflow.com
🌐 stackoverflow.com
python - Read CSV items with column name - Stack Overflow
... If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. ... Sign up to request clarification or add additional context in comments. ... You can use a csv.DictReader instance to get this behaviour. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-csv › reading › reading › importing-csv-contents-using-custom-field-names
Read and Write CSV in Python | Learn Python | Vertabelo Academy
import csv with open('departments.csv') as csv_file: csv_reader = csv.DictReader(csv_file, fieldnames=['Department Name', 'Number of Employees', 'Department Budget']) line_count = 0 for row in csv_reader: if line_count > 0 and float(row['Department ...
🌐
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!
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']
🌐
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 - restkey & restval :- If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey. ... We can use the field names argument while initiating the object to change the column’s name. It will change the default values of the column in our code. However, it will not change the column name in the CSV file. Let’s see the sample code. # importing DictReader class from csv module from csv import DictReader # opening csv file named as airtravel.csv with open('airtravel.csv','r') as file: reader = DictReader(file,fieldnames=['New-Month','FY-1958','FY-1959','FY-1960']) print("Data:") # printing each row of table as dictionary for row in reader: print(row)
🌐
Reddit
reddit.com › r/learnpython › csv.dictreader when one of my fields is a list
r/learnpython on Reddit: csv.DictReader when one of my fields is a list
August 29, 2023 -

I would like to read a csv into a dict but one of my fields is a list. Like so:

item, num_ordered, people

apple, 4, ['Janet', 'Sam']

grape, 1, ['Stu', 'Jenny']

I used csv.DictReader without the `fieldnames` kwarg so the header row became the names of the keys. But it's picking up the commas in the lists as the end of a field. How do I get it to recognize that these are lists?

🌐
ProgramCreek
programcreek.com › python › example › 1483 › csv.DictReader
Python Examples of csv.DictReader
def get_msr_paraphrase() -> Dict[str, List[Dict[str, str]]]: url = 'https://raw.githubusercontent.com/wasiahmad/paraphrase_identification/master/dataset/msr-paraphrase-corpus/msr_paraphrase_{}.txt' # NOQA root = download.get_cache_directory(os.path.join('datasets', 'msr_paraphrase')) def creator(path): dataset = {} fieldnames = ('quality', 'id1', 'id2', 'string1', 'string2') for split in ('train', 'test'): data_path = gdown.cached_download(url.format(split)) with io.open(data_path, 'r', encoding='utf-8') as f: f.readline() # skip header reader = csv.DictReader(f, delimiter='\t', fieldnames=fie
Find elsewhere
🌐
Demo2s
demo2s.com › python › python-csv-dictreader.html
Python csv.DictReader
# importing the csv library import csv # w w w . de m o 2 s .c o m # opening the csv file with open('data.csv') as csv_file: # reading the csv file using DictReader csv_reader = csv.DictReader(csv_file) # converting the file to dictionary # by first converting to list # and then converting the list to dict dict_from_csv = dict(list(csv_reader)[0]) # making a list from the keys of the dict list_of_column_names = list(dict_from_csv.keys()) # displaying the list of column names print("List of column names : ", list_of_column_names) PreviousNext ... Python csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
🌐
GeeksforGeeks
geeksforgeeks.org › get-column-names-from-csv-using-python
Get column names from CSV using Python - GeeksforGeeks
April 7, 2025 - Display the list. ... import csv with open('data.csv') as csv_file: csv_reader = csv.DictReader(csv_file) header = list(dict(next(csv_reader)).keys()) print("List of column names:", header)
🌐
Brodan
brodan.biz › blog › parsing-csv-files-with-python
Parsing CSV Files with Python's DictReader - Brodan.biz
August 24, 2018 - The DictReader class basically creates a CSV object that behaves like a Python OrderedDict. It works by reading in the first line of the CSV and using each comma separated value in this line as a dictionary key. The columns in each subsequent row then behave like dictionary values and can be accessed with the appropriate key. If the first row of your CSV does not contain your column names, you can pass a fieldnames parameter into the DictReader's constructor to assign the dictionary keys manually.
🌐
Reddit
reddit.com › r/learnpython › when using reader or dictreader from the csv module, why do you need to access the return value while the file is still open?
r/learnpython on Reddit: When using reader or DictReader from the csv module, why do you need to access the return value while the file is still open?
August 7, 2023 -

Ok, this will make more sense. Why does this work:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        print(row)

But this gives an error that the file is closed:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)

for row in csv_reader:
    print(row)

Traceback (most recent call last):
File "c:\Users\John\Documents\Python\test_project\test2.py", line 5, in <module> for row in csv_reader: File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 110, in next self.fieldnames File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 97, in fieldnames self._fieldnames = next(self.reader) ^ 
ValueError: I/O operation on closed file.

Does DictReader (and also reader) not just run once and return a value? Why is csv_file being accessed after the line it's used in?

Thanks!

🌐
DEV Community
dev.to › thumbone › dumping-data-with-pythons-csv-dictwriter-1g0
Dumping Data with Python's CSV DictWriter - DEV Community
May 16, 2025 - ... 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'}) ...
🌐
Arashout
arashout.site › posts › field_by_field_comparison_with_dictreader
Python's csv.DictReader for easy field by field comparisons
This is where the power of csv.DictReader shines. # Helper method for finding the row we are looking for. # Could have been more efficient if I stored it in hash-set but the CSVs are pretty small def find_row_by_code(c: str, rows: list) -> dict: for row in rows: if c == row[PRIMARY_KEY]: return row raise ValueError("code {} not found".format(c)) # Use set operations to find common rows codes_in_both = codes_t.intersection(codes_p) print("{0} codes in both test and prod".format(len(codes_in_both))) # defaultdict for collecting the differences in EACH field from collections import defaultdict differences = defaultdict(list) # Some columns that I don't care about...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python read csv file
How to Read a CSV File in Python Using csv Module
March 30, 2025 - Code language: Python (python) ... of field names to the DictReader() constructor like this: import csv fieldnames = ['country_name', 'area', 'code2', 'code3'] with open('country.csv', encoding="utf8") as f: csv_reader = ...