Skip to main content

Reading CSV File using Python

In our Python tutorial, you have learned how to write CSV file in Python. In this tutorial, you will learn how to read CSV File in Python.

CSV (comma-separated values) file is a delimited text file. The file consists of one or more lines of data record. Each data record consists of values separated by commas, all the lines of a CSV file have the same number of values.

Here in this tutorial, we will implement how to read a CSV file to get file data. We will use csv module from Python to read CSV file.

So let’s proceed with coding:

Reading a CSV File in Python

As we are going to implement to read csv file to get data. So we will have following CSV in a employee.csv file. You can create CSV file employee.csv using below.

#employee.csv

"name","age","country"
"Smith", "32", "Australia"
"William", "30", "Newyork"
"Andre", "20", "Germany"
"Root", "40", "France"
"Andy", "35", "Britain"

To read the CSV file using Python, we need to import csv module from Python to read a CSV file.

import csv

then we will open the CSV file using open() function. The function will return file object.

file = open('path/csv_file', 'r')

we need to pass the file object file to the DictReader() function of the csv module. The DictReader() function returns a csv reader object.

csvReader = csv.DictReader(file) 

we will iterate over csvReader object for each line and get value of each field from line onject.

for line in csvReader:    
        print(line)

As we have used DictReader() fucntion, we can access the value field name like below.

line['name']

The following is the complete code for reading CSV file.

#read.py

import csv
with open('employee.csv', 'r') as file:    
    csvReader = csv.DictReader(file)    
    for line in csvReader:        
        print(f"Name: {line['name']}, Age : {line['age']}, Country: {line['country']}")
        

The above will print following data from CSV file.

Name: Smith, Age :  "32", Country:  "Australia"
Name: William, Age :  "30", Country:  "Newyork"
Name: Andre, Age :  "20", Country:  "Germany"
Name: Root, Age :  "40", Country:  "France"
Name: Andy, Age :  "35", Country:  "Britain"