Python Read CSV File Example Tutorial

Published On: 05/01/2023 | Category: Python


Hi Guys,

In this tutorial, you will learn python read csv examples. you'll learn python get data from csv file. We will look at example of python read csv file example. I explained simply about python program to read data from csv file. You just need to some step to done read data from csv file python.

We'll use one demo in this instance. ID, Name, and Email fields in a demo.csv file. Then, to read data from a csv file, we will utilise the open() and reader() functions.

Without further ado, let's look at the code example below:

So let's see bellow example:

Example 1: Python Read CSV File

main.py
from csv import reader
  
# open demo.csv file in read mode
with open('demo.csv', 'r') as readObj:
  
    # pass the file object to reader() to get the reader object
    csvReader = reader(readObj)
  
    # Iterate over each row in the csv using reader object
    for row in csvReader:
        # row variable is a list that represents a row in csv
        print(row)
Output
['ID', 'Name', 'Email']
['1', 'Bhavesh Sonagra', '[email protected]']
['2', 'Nikhil Patel', '[email protected]']
['3', 'Piyush Kamani', '[email protected]']

Example 2: Python Read CSV File without Header

main.py
from csv import reader
    
# skip first line from demo.csv
with open('demo.csv', 'r') as readObj:
  
    csvReader = reader(readObj)
    header = next(csvReader)
  
    # Check file as empty
    if header != None:
        # Iterate over each row after the header in the csv
        for row in csvReader:
            # row variable is a list that represents a row in csv
            print(row)
Output
['ID', 'Name', 'Email']
['1', 'Bhavesh Sonagra', '[email protected]']
['2', 'Nikhil Patel', '[email protected]']
['3', 'Piyush Kamani', '[email protected]']

Example 3: Python Read CSV File Line By Line

main.py
from csv import DictReader
  
# open demo.csv file in read mode
with open('demo.csv', 'r') as readObj:
  
    # Pass the file object to DictReader() to get the DictReader object
    csvDictReader = DictReader(readObj)
  
    # get over each line as a ordered dictionary
    for row in csvDictReader:
        # row variable is a dictionary that represents a row in csv
        print(row)
Output
{'ID': '1', 'Name': 'Bhavesh Sonagra', 'Email': '[email protected]'}
{'ID': '2', 'Name': 'Nikhil Patel', 'Email': '[email protected]'}
{'ID': '3', 'Name': 'Piyush Kamani', 'Email': '[email protected]'}

It will help you....