Reading Rows from a CSV File in Python

20 Dec, 2021
CSV stands for Comma Separated Values. This file format is a delimited text file that uses a comma as a delimiter to separate the text present in it. Or in other words, CSV files are used to store data in tabular form. As per the name suggested, this file contains the data which is separated by a comma and every line of a file is considered a record. We can create the CSV file either from notepad or using excel. 
Example:
Geeks,for,geeks
one,of,the,
top,learning,platform
We can create a CSV file using the following ways:
1. Using Notepad: We can create a CSV file using Notepad. In the Notepad, open a new file in which separate the values by comma and save the file with .csv extension.
2. Using Excel: We can also create a CSV file using Excel. In Excel, open a new file in which specify each value in a different cell and save it with filetype CSV.
To read data row-wise from a CSV file in Python, we can use reader and DictReader which are present in the CSV module allows us to fetch data row-wise.
Using reader we can iterate between rows of a CSV file as a list of values. It iterates over all rows in a CSV file and fetches data in each row as a list. reader() method is present in CSV library. So to use this reader method, first we need to import the CSV library. reader object accepts a single parameter called fileObject (a variable that holds the CSV file). 
Syntax:
csv.reader(fileobject)
Steps to read CSV file:
Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method.
with open('filename') as fileObject
While loading the file by specifying path along with filename, if you got any unicode error then append r before path of filename
with open(r'path/filename') as fileObject 
Step 2: Create a reader object by passing the above-created file object to the reader function.
reader_obj = csv.reader(file_obj)
Step 3: Use for loop on reader object to get each row.
Example:
Consider a CSV file named “samplecsv.csv”. This file contains the following data:
Id,Name,Rating
1,Akhil,4
2,Babu,3
3,Nikhil,5
Python3
# Python program to read CSV file line by line# import necessary packagesimport csv  # Open file with open('samplecsv.csv') as file_obj:          # Create reader object by passing the file     # object to reader method    reader_obj = csv.reader(file_obj)          # Iterate over each row in the csv     # file using reader object    for row in reader_obj:        print(row)
Output:
['Id', 'Name', 'Rating']
['1', 'Akhil', '4']
['2', 'Babu', '3']
['3', 'Nikhil', '5']
Reading CSV file without header
Everything is fine with the above example but if we don’t want column names to fetch or we can say we don’t want to read the header of the file, then we use the next() method on the file object before creating the reader object so that it skips the headings.
Python3
# Python program to read CSV file without header  # Import necessary packagesimport csv  # Open filewith open('samplecsv.csv') as file_obj:          # Skips the heading    # Using next() method    heading = next(file_obj)          # Create reader object by passing the file     # object to reader method    reader_obj = csv.reader(file_obj)          # Iterate over each row in the csv file     # using reader object    for row in reader_obj:        print(row)
Output:
['1', 'Akhil', '4']
['2', 'Babu', '3']
['3', 'Nikhil', '5']
Explanation: The above code is almost the same as the code in the above example but a slight change is we use the next function here that helps us to skip the column names while accessing data from a CSV file i.e. first row. If column names are required then we access them from the heading object i.e. return the result of the next method.
When using a reader() method we can iterate over a CSV file as a list but using the DictReader class object we can iterate over a CSV file row by row as a dictionary. This DictReader method is present in the csv library. So to use it first we need to import the csv library. DictReader() accepts a single parameter called fileObject (a variable that holds the csv file). 
Syntax
csv.DictReader(fileobject)
Steps to read CSV file:
Step 1: Load the CSV file using the open method in a file object.
with open('filename') as fileObject
Step 2: Create a reader object with the help of DictReader method using fileobject.
reader_obj = csv.DictReader(file_obj)
This reader object is also known as an iterator can be used to fetch row-wise data.
Step 3: Use for loop on reader object to get each row.
Example:
Python3
# Python3 program to read CSV file using DictReader  # Import necessary packagesimport csv  # Open filewith open('samplecsv.csv') as file_obj:          # Create reader object by passing the file    # object to DictReader method    reader_obj = csv.DictReader(file_obj)          # Iterate over each row in the csv file    # using reader object    for row in reader_obj:        print(row)
Output:
OrderedDict([('Id', '1'), ('Name', 'Akhil'), ('Rating', '4')])
OrderedDict([('Id', '2'), ('Name', 'Babu'), ('Rating', '3')])
OrderedDict([('Id', '3'), ('Name', 'Nikhil'), ('Rating', '5')])
Explanation: In the code, first we loaded the CSV file named samplecsv.csv and then created a reader_object that can be iterated to fetch each row. The returned result is in the form of Key-Value pair indicates it as a dictionary. So using DictReader we read data row by row as a Dictionary.
Picked
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.