Python - Read data from CSV file


python logo

In this tutorial we will learn to read CSV file in Python.

What is a CSV file?

A CSV or Comma Separated Values is a plain text file containing tabular data in printable ASCII or Unicode characters.

Points to note!

CSV files are saved with .csv extension.

You can create CSV files using text editors like Notepad, Sublime Text etc.

You can also use application like MS-Excel to create CSV files.

Sample CSV file

In the following example we have the content of a sample CSV file containing 4 rows and 3 columns.

1,Jane Doe,10
2,John Doe,9

The first row of the file is generally the name of the columns.

The above file has 3 columns - id, name and score. The remaining three rows contain the data.

Import the csv module

To work with CSV files in Python we take help of the csv module.

Import the csv module by writing the following line.

import csv

Reading CSV file

To read CSV file data we take help of the reader() method of the csv module.

In the following Python program we are reading the content of the data.csv file and printing its content in the console.

Content of the data.csv file.

1,Jane Doe,10
2,John Doe,9

Python code to read CSV file.

# import module
import csv

    # open file
    fobj = open('data.csv', 'r')
    # reader object
    csvReader = csv.reader(fobj)
    # get the field name
    fields =
    # total columns
    columnsCount = len(fields)
    # iterate the rows
    rows = []
    for row in csvReader:
    # print rows
    for r in rows:
        for i in range(columnsCount):
            print(fields[i] + " = " + r[i])
    print("An error occurred while reading the file.")


The above Python code will give us the following output.

id = 1
name = Jane Doe
score = 10
id = 2
name = John Doe
score = 9
id = 3
name = Alice
score = 10