EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials File Handling Python Tutorial Python Read CSV File
 

Python Read CSV File

Priya Pedamkar
Article byPriya Pedamkar

Updated March 27, 2023

python reead csv file

 

 

Introduction to Python Read CSV File

In this article, we will learn about Python Read CSV File. CSV Module is a built-in module in Python. In order to use it, one needs to just import it in the python environment. Like:

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

import csv

As the “csv” module is part of the standard library, so one needs not to install. Here csv stands for Comma Separated Values format files (which a tabular form of storing data, easy to read and understand by a human).

A csv file looks like this:

Sr_No, Emp_Name, Emp_City
1, Obama, England
2, Jackson, California

One can notice, commas separate elements in the csv file. There are many functions of the csv module, which helps in reading, writing and with many other functionalities to deal with csv files.

Examples to Implement Python Read CSV File

Let’s explore more about csv through some examples:

Read the CSV File

Example #1

One needs to set the directory where the csv file is kept.

Code:

import os
os.chdir("My Folder/Personnel/EDUCBA/Jan")

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file)
    for each_row in reader:
        print(each_row)

Output:

CSV File

Explanation of the above code: As one can see, “open(‘Emp_Info.csv’)” is opened as the file.”csv.reader()” is used to read the file, which returns an iterable reader object. Here csv.reader() is used to read csv file, however the functionality is customizable.

Example #2

Like, if the file is a semi-colon separated file.

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file,delimiter  = ';')
    for each_row in reader:
        print(each_row)

Once the reader object is ready, it is looped around to print the content line by line. Delimiter helps to specify the separator of a file.

Try-Finally in csv.reader()

Code:

import csv
file = open('Emp_Info.csv', 'r')
try:    
    reader = csv.reader(file)
    for each_row in reader:
        print(each_row)
finally:
    file.close()

Output:

python read csv file - 3

Example #3

Now let’s say we have a csv file that looks like this:

python read csv file - 4

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file)
    for each_row in reader:
        print(each_row)

Output:

csv.reader()

  • As one can notice, commas present in “EMP_Address” will make it split into different columns.
  • In order to overcome this issue, we can use one parameter inside the csv.reader, i.e. quote char.

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file,quotechar="'")
    for each_row in reader:
        print(each_row)

Output:

python read csv file - 6

This quote char helps in the surrounding values of the file with special values/characters. Like here, we quoted all values of the cell with a single inverted comma.

Example #4

Now let say our file looks like this:

python read csv file - 7

One can notice the “whitespaces” before the 2nd and 3rd columns. When this will be read through our code:

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file)
    for each_row in reader:
        print(each_row)

Output:

python read csv file - 8

  • This kind of result is not expected, and hence we want to skip those whitespaces.
  • Hence,the parameter “skipinitialspace” needs to be utilized in csv.reader():

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file,skipinitialspace=True)
    for each_row in reader:
        print(each_row)

Output:

python read csv file - 9

Example #5

Now say we have double quotes in our cells.

double quotes

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    #reader = csv.reader(file,quoting=csv.QUOTE_NONE)
    reader = csv.reader(file,doublequote=True)
    for each_row in reader:
        print(each_row)

Output:

double quotes

  • Here, the consecutive double quote will be converted to a single quote when doublequote = True.
  • Hence make doublequote = False.

Code:

import csv
with open('Emp_Info.csv', 'r') as file:
    reader = csv.reader(file,doublequote=False)
    for each_row in reader:
        print(each_row)

Output:

False.

Here, consecutive double quotes will be displayed as it is.

Reading CSV File using csv.DictReader()

Code:

import csv
with open("Emp_Info.csv", 'r') as file:
    csv_reader = csv.DictReader(file)
    for each_row in csv_reader:
        print(dict(each_row))

Output:

using csv.DictReader()

  • Here csv_reader is csv.DictReader() object. Here csv.DictReader() helps reading the csv file in the form of a dictionary, where the first row of the file becomes “keys” and the rest of all rows become “values”.
  • The first row had “Sr_No”,” Emp_Name”, and “Emp_City”, so these became keys, whereas the rest rows become their value.
  • Csv.DictReader() in itself returns a dictionary of each row, that when doing dict() explicitly as per your requirement is futile.
Note: One important concept of “dialect” comes into the picture while using the csv module. Dialect helps in defining a set of parameters, particularly to csv format to be used while reading a set of csv files. One has the flexibility to define its own set of the parameter using “register_dialect”.

Code:

csv.register_dialect(
    'mydialect',
    delimiter = ';',
    skipinitialspace = True,
    quotechar = '"',
    doublequote = True, 
)

Now this defined dialect can be used directly while reading or writing a csv file.

reader = csv.reader(csv_file, dialect='mydialect')

Conclusions

As we saw above, how important is the concept of csv reading in Python? There are various methods and parameters related to it. Every parameter has its significance while dealing with csv reading as well as writing a file. One needs to be familiar with it and practice it to get a good grip over it.

Recommended Articles

This is a guide to Python Read CSV File. Here we discuss an introduction, csv through some examples with proper codes and outputs. You can also go through our other related articles to learn more –

  1. Lowercase in Python
  2. Python Global Variable
  3. Python if main
  4. Python List Functions

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW