Skip to content

All topics  /  Python

Read a CSV File in Python Tutorial Example

Python ·

Development teams using “Read a CSV File in Python Tutorial Example” in client or internal work can use learn more here to document project effort and hand-offs, then assess the record against delivered functionality, tests and agreed outcomes.

Validate current syntax, security guidance and supported versions through Python.org before using the example in production.

Hi Dev,

Now, let's see tutorial of read a CSV file in python tutorial example. step by step explain read data from csv file python. you will learn python program to read data from csv file. it's simple example of python get data from csv file.

In this example, we will take one demo.csv file with ID, Name and Email fields. Then, we will use open() and reader() functions to read csv file data.

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', 'Hardik Savani', '[email protected]']
['2', 'Vimal Kashiyani', '[email protected]']
['3', 'Harshad Pathak', '[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:

['1', 'Hardik Savani', '[email protected]']
['2', 'Vimal Kashiyani', '[email protected]']
['3', 'Harshad Pathak', '[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': 'Hardik Savani', 'Email': '[email protected]'}
{'ID': '2', 'Name': 'Vimal Kashiyani', 'Email': '[email protected]'}
{'ID': '3', 'Name': 'Harshad Pathak', 'Email': '[email protected]'}