In this tutorial, we will learn for reading CSV files in Python. The file format known as CSV (Comma Separated Values) holds data in tabular form. The fields are separated by commas in a CSV file, and the file line includes the data record.
There are basically two common methods of reading a CSV file in Python. First is module
csv
, and the second is the Pandas library.
Using
csv
module and reader class
It is a common module for reading or writing CSV files in Python. Here are the steps, we will follow to read a CSV File:
- Import
csv
module. - Open the CSV file in read mode.
- Create an object by calling the class
reader
of the modulecsv
. Reader class reads the file line by line and returns the object. - Run a loop for showing the data.
1 2 3 4 5 6 7 | import csv #open the csv file with open('users.csv', mode='r') as csv_file: #read the CSV file csv_reader = csv.reader(csv_file) for row in csv_reader: print(row) |
Using
csv
module and
DictReader
class
DistReader class maps the first line of data as keys and returns data in the dictionary format.
Steps for reading a CSV file using class
DictReader
:
- Import
csv
module. - Open the CSV file in read mode.
- Create an object by calling the class
DictReader
of the modulecsv
. Reader class reads the file line by line and returns the object. - Run a loop for showing the data.
1 2 3 4 5 6 7 8 | import csv #open the csv file with open('users.csv', mode='r') as csv_file: #read csv using DictReader class to show data in dictionary csv_reader = csv.DictReader(csv_file) #display the contents of the CSV file for row in csv_reader: print(row) |
You can check the python CSV reader code using the module
csv
on GitHub.
Reading CSV Using Pandas Library
Steps for reading a CSV file using Panda Library:
- Import pandas module.
- Use
read_csv
function and pass the file to this function as an argument. - Print data.
1 2 3 4 | import pandas #open the csv file csv_file = pandas.read_csv('users.csv') print(csv_file) |
You can check the python CSV reader code using the Pandas module on GitHub.