For Python 3

Remove the rb argument and use either r or don't pass argument (default read mode).

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

For Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.

Answer from Katriel on Stack Overflow
Top answer
1 of 4
175

For Python 3

Remove the rb argument and use either r or don't pass argument (default read mode).

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

For Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.

2 of 4
128

Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.

Assuming your file is named myclone.csv and contains

workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0

this code should give you an idea or two:

>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
...    column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
...   for h, v in zip(headers, row):
...     column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>

To get your numeric values into floats, add this

converters = [str.strip] + [float] * (len(headers) - 1)

up front, and do this

for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

for each row instead of the similar two lines above.

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.4 documentation - PyData |
Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment='#', parsing #empty\na,b,c\n1,2,3 with header=0 will result in 'a,b,c' being treated as the header. ... Encoding to use for UTF when reading/writing (ex. 'utf-8'). List of Python standard encodings .
Discussions

Reading and writing a csv file with header
I am trying to complete a task to read a csv file which is a list of a dictionary of names and houses, then write it to another csv file with first name and last name placed in correct order. I am also trying to place a header at the top of the written csv file. More on discuss.python.org
🌐 discuss.python.org
2
0
May 31, 2022
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
How can I read only the header column of a CSV file using Python? - Stack Overflow
I am looking for a a way to read just the header row of a large number of large CSV files. Using Pandas, I have this method available, for each csv file: >>> df = pd.read_csv(PATH_TO_CS... More on stackoverflow.com
🌐 stackoverflow.com
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 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
AskPython
askpython.com › python-modules › pandas › pandas-read-csv-with-headers
How to Read CSV with Headers Using Pandas? - AskPython
January 21, 2026 - The DataFrame that gets created uses these header values as the column index, which means you can reference columns by name instead of position. This matters because working with named columns makes your code readable and maintainable. import pandas as pd # These are equivalent df = pd.read_csv('sales_data.csv') df = pd.read_csv('sales_data.csv', header=0) # Access columns by their header names print(df['product_name']) print(df['revenue'])
🌐
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 - This automatically closes the file when done. ... Assign a pointer to the file: csv_file. ... csv.DictReader reads each row of the CSV file as a dictionary, where the keys are the column headers...
🌐
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.
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. ... The Python Enhancement Proposal which proposed this addition to Python.
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-column-names-from-csv-using-python
Get column names from CSV using Python - GeeksforGeeks
June 30, 2025 - Converting the CSV file to a data frame using the Pandas library of Python. Below is the snapshot of the dataset we are going to use in this article for demonstration, you can download it from here. This method reads the CSV file using the csv.reader and then prints the first row, which contains the column names. ... 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)
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Reading and writing a csv file with header - Python Help - Discussions on Python.org
May 31, 2022 - I am trying to complete a task to read a csv file which is a list of a dictionary of names and houses, then write it to another csv file with first name and last name placed in correct order. I am also trying to place a …
🌐
Delft Stack
delftstack.com › home › howto › python › python read csv with header
How to Read a CSV With Its Header in Python | Delft Stack
February 2, 2024 - Using the next() method, we first fetched the header from csv_reader and then iterated over the values using a for loop.
🌐
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
The header row contains the column names, which are essential for understanding the structure and meaning of the data. To read the header row in a CSV file, you can use the csv.reader() function from the csv module.
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-csv › reading › reading › recognizing-the-header-line
Read and Write CSV in Python | Learn Python | Vertabelo Academy
If we know that there is a header line in our CSV file, we can make good use of it: import csv with open('departments.csv') as csv_file: csv_reader = csv.reader(csv_file) line_count = 0 for row in csv_reader: if line_count == 0: print('Columns found:', ", ".join(row)) else: print('Department found:', ", ".join(row)) line_count += 1
🌐
ListenData
listendata.com › home › pandas
Python Pandas : 15 Ways to Read CSV Files
import pandas as pd mydata = pd.read_csv("C:/Users/deepa/Documents/workingfile.csv", header = 1) header=1 tells python to pick header from second row. It's setting second row as header. It's not a realistic example. I just used it for illustration so that you get an idea how to solve it.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-get-column-names-from-csv-file-in-pythonexample.html
How to Get Column Names from CSV File in Python? - ItSolutionstuff.com
October 30, 2023 - ... from csv import reader # skip first line from demo.csv with open('demo.csv', 'r') as readObj: csvReader = reader(readObj) # Get CSV File Columns Name header = next(csvReader) print(header)
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-read-csv-using-pandas-read_csv
Pandas Read CSV in Python - GeeksforGeeks
Pandas Read CSV in Python · read_csv() function in Pandas is used to read data from CSV files into a Pandas DataFrame. A DataFrame is a data structure that allows you to manipulate and analyze tabular data efficiently.
Published   April 28, 2026
🌐
Reddit
reddit.com › r/learnpython › how can i check if a csv file has headers
r/learnpython on Reddit: How Can I Check if a CSV File has Headers
May 12, 2021 -

I am making a terminal based app. One of the features of the app is it stores user statistics by writing they're progress into a csv file.

I can write information into the csv file perfectly, however I am trying to figure out how to write the headers into the csv file correctly.

I am trying to create a conditional lets say has_headers that if it returns True it will continue on as normal, but if has_headers is False will write the headers into the first line of the csv.

🌐
Saturn Cloud
saturncloud.io › blog › how-to-prevent-pandas-readcsv-from-treating-the-first-row-as-header-of-column-names
How to Prevent Pandas readcsv from Treating the First Row as Header of Column Names | Saturn Cloud Blog
May 1, 2026 - One of the most common tasks when working with pandas is reading CSV files into a pandas DataFrame using the read_csv method. By default, read_csv assumes that the first row of the CSV file contains the header of the DataFrame.
🌐
Analytics Vidhya
analyticsvidhya.com › home › read csv files in python
Read CSV Files in Python - Analytics Vidhya
January 9, 2026 - Here’s a simple guide on how to use Python to read CSV file ... Iterate through the rows of the CSV file using a ‘for’ loop and the DictReader object to see the field names as keys along with their respective values. ... We can write to a CSV file in multiple ways. The csv.writer() function returns a writer object that converts the input data into a delimited string. For example, let’s assume we are recording the data of 3 students (Name, M1 Score, M2 Score) header = ['Name', 'M1 Score', 'M2 Score'] data = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]]
🌐
jdhao's digital space
jdhao.github.io › 2018 › 05 › 13 › read-write-csv-file-with-header
How to Read and Write CSV Files in Python · jdhao's digital space
September 29, 2022 - import pandas as pd # delimiter ... code will be Pandas dataframe object. If the csv file you have does not have header, you should use header=None when reading this file:...
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']