How to Read CSV File Line by Line in Python?

27-Dec-2022

.

Admin

How to Read CSV File Line by Line in Python?

Hi Dev,

In this post, we will learn how to read csv file line by line in python. We will use python read large csv file line by line. you can understand a concept of python read csv file line by line. I’m going to show you about how to read csv file row by row in python. you will do the following things for how to read csv file line by line in python.

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

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', 'hardik@gmail.com']

['2', 'Vimal Kashiyani', 'vimal@gmail.com']

['3', 'Harshad Pathak', 'harshad@gmail.com']

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', 'hardik@gmail.com']

['2', 'Vimal Kashiyani', 'vimal@gmail.com']

['3', 'Harshad Pathak', 'harshad@gmail.com']

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': 'hardik@gmail.com'}

{'ID': '2', 'Name': 'Vimal Kashiyani', 'Email': 'vimal@gmail.com'}

{'ID': '3', 'Name': 'Harshad Pathak', 'Email': 'harshad@gmail.com'}

#Python