How to Read CSV File Line by Line in Python?

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


Hi Dev,

In this example i will explain you how to read csv file line by line in python. step by step explain how to read csv file row by row in python. This article will give you simple example of python read csv file line by line.

We will use one demonstration demo.csv. ID, Name, and Email fields are included in the csv file. Then, we'll use the open(), DictReader, and reader() functions to read csv file data into a list row by row.

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
['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....