How to read a CSV file in Python 

In this Python tutorial, we will discuss how to read csv files using different methods and techniques.

There are 5 methods to read a CSV file in Python, which are shown below:

  • Using csv module
  • Using Pandas
  • Using DictReader() class
  • Using the built-in open() function
  • Using the loadtxt() function

What is a CSV file in python?

In python CSV is Comma Separated Values, it is a plain text file which is used to arrange the tabular data. CSV performs data interchange and it must be saved with.CSV file.

Python Read CSV File

Here we will discuss all 5 methods to read CSV in Python. And for each method, we have have stated an example which is given below.

Method-1 Python Read CSV File using csv module

Python CSV module offers features for reading, writing, and manipulating CSV files.

sam@gmail.com,sammy,33
john@dey.com,john,43
stephan@cook.com,stephan,45

Store the above data in the file using any text editor and save the file with the extension (.csv), the saved file might look like this:

Python Read CSV File
datafile.csv
# Import the csv module
import csv 


# Open the datafile.csv file in read mode using the with statement to ensure proper handling #of the file
with open("datafile.csv", 'r') as csvfile:

# Create a csv.reader object from the file object 
    rows = csv.reader(csvfile)                
    for row in rows:                          # Loop through each row in the csv.reader object
        print(row)                            # Print each row to the console

The above code uses the csv module to read the contents of a CSV file named “datafile.csv”.

  • It first opens the file using the with statement, which automatically handles closing the file when the block of code is finished executing.
  • It then creates a csv.reader object from the file object, which can be used to read the contents of the file row by row. Finally, it loops through each row in the csv.reader object and prints the row to the console.
Python Read CSV File
Python Read CSV File

Read: Get current directory Python

Method-2: Python Read CSV File using Pandas

Pandas is a popular library in Python for data manipulation and analysis. It provides an easy-to-use method for reading CSV files.

 # Import the pandas module and alias it as 'pd'
import pandas as pd

# Read the 'datafile.csv' file and store it in a pandas DataFrame object named 'data'
data = pd.read_csv('datafile.csv') 

# Print the contents of the 'data' DataFrame object to the console
print(data)                      

The above code uses the pandas module to read the contents of a CSV file named ‘datafile.csv’ and store it in a DataFrame object named ‘data’.

  • The pd.read_csv() method automatically parses the CSV file and returns a DataFrame object. Finally, the print() statement is used to display the contents of the ‘data’ DataFrame object to the console.

Read: Python copy file

Method-3: Python Read CSV File using DictReader() class

The csv.DictReader() class is a convenient way to read CSV files into Python dictionaries. Each row of the CSV file is represented as a dictionary where the keys are the column headers and the values are the corresponding values in the row.

# Import the csv module
import csv                       

# Open the 'datafile.csv' file in read mode using the with statement to ensure proper handling #of the file object
with open('datafile.csv', 'r') as file: 


# Create a csv.DictReader object from the file object, which reads the file and returns an #ordered dictionary for each row
    reader = csv.DictReader(file)
# Loop through each row in the csv.DictReader object        
    for row in reader: 
# Print each row to the console                  
        print(row)                       

The above code uses the csv module to read the contents of a CSV file named ‘datafile.csv’ and create an ordered dictionary for each row in the file.

  • The with statement is used to automatically handle the opening and closing of the file object. The csv.DictReader() method is used to create a dictionary object that maps the values in each row to their corresponding column names, using the first row of the CSV file as the header row.
  • Finally, the for loop is used to iterate through each row in the csv.DictReader object and print it to the console.

Read: Os change directory Python

Method-4: Python Read CSV File using the built-in open() function

You can also use the built-in open() function in Python to read a CSV file.

# Open the 'datafile.csv' file in read mode using the with statement to ensure proper handling #of the file object
with open('datafile.csv', 'r') as file:  

# Loop through each line in the file object
    for line in file:
# Remove any leading or trailing whitespace from the line using the strip() method, then split #the line into a list of values using the comma separator and print it to the console                   
        print(line.strip().split(',')) 

The code above opens a CSV file named “datafile.csv” and reads its contents using a file object.

  • It then loops through each line in the file, removes any leading or trailing whitespace, and splits the line into a list of values using the comma separator. Finally, it prints each list of values to the console.

Read: Python File methods

Method-5: Python Read CSV File using the loadtxt() function

The numpy.loadtxt() function can be used to read a CSV file into a NumPy array.

# Import NumPy library with an alias 'np' for ease of use
import numpy as np

# Load data from a CSV file named 'datafile.csv' with ',' as the delimiter
data = np.loadtxt('datafile.csv', delimiter=',')

# Print the loaded data, which is stored in a NumPy array
print(data)

The above code imports the NumPy library with an alias ‘np’ and then loads data from a CSV file named ‘datafile.csv’ with ‘,’ as the delimiter using the ‘loadtxt’ function provided by NumPy.

  • The loaded data is stored in a NumPy array, which is then printed using the ‘print’ function.

You may also like to read the following Python tutorials.

In this Python tutorial, we have covered how to read CSV files using 5 different methods:

  • Using csv module
  • Using Pandas
  • Using DictReader() class
  • Using the built-in open() function
  • Using the loadtxt() function