Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict


Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python


Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort


Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

CSV Module In Python


CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores tabular data in the form of plain text. Here the commas are used to separate each column within the row and every part of the data is separated with a comma.

CSV is a simple format for data exchange as it is general and, simpler. A CSV file is represented when it is saved with .CSV file extension.

Working with Python CSV files:

Before using the functions to CSV module we have to import it using the below code:
import csv

The CSV library provides various functions to perform read and write operations in the CSV files.

Reading the CSV file:

To perform read operation in CSV file. first, we have to generate the reader object using the reader function.

The Python's built-in function open() returns a file object by which the csv file as a text file is opened then it is passed to the reader.

Here’s the employee_joining.txt file:

name, department,joining month
Raam,Accounting, November
Aakash,IT, March

Below is the code to read the above file:

import csv

with open('employee_joining.txt') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=',')

    line_count = 0

    for row in csv_reader:

        if line_count == 0:

            print(f'Column names are {", ".join(row)}')

            line_count += 1


            print(f'\t{row[0]} works in the {row[1]} department, and joined in {row[2]}.')

            line_count += 1

    print(f'Processed {line_count} lines.')


Column names are name, department, joining month

Raam works in the Accounting department, and joined in November.

Aakash works in the IT department, and joined in March.

Here, the reader returned each row is a list of string elements and it contains the data obtained by eliminating the delimiters.

Reading a CSV file as a dictionary:

We can perform the reading operation of CSV data directly with the dictionary. Here we can read the csv files using dictreader.

The results are represented as a dictionary in which the header row is placed as the key and other rows are placed as values.

Again, the input file is employee_joining.txt file:

name, department,joining month
Raam,Accounting, November
Aakash,IT, March

Code to read as a dictionary:

import csv

with open('employee_joining.txt', mode='r') as csv_file:

    csv_reader = csv.DictReader(csv_file)

    line_count = 0

    for row in csv_reader:

        if line_count == 0:

            print(f'Column names are {", ".join(row)}')

            line_count += 1

        print(f'\t{row["name"]} works in the {row["department"]} department, and joined in {row["birthday month"]}.')

        line_count += 1

    print(f'Processed {line_count} lines.')

Output is the same as before:

Column names are name, department, birthday month

Raam works in the Accounting department, and joined in November.

Aakash works in the IT department, and joined in March.

Additional Python CSV reader parameters:

Different styles of CSV files are handled by the reader object via defining optional parameters.

Some parameters are as shown below:

  • quotechar defines the character that is used to enclose fields that includes the delimiter character. quote (' " ') is the default.
  • delimiter definesthe character that is used to divide each field. comma (',') is default.
  • escapechar defines the character that is used to skip the delimiter character. no escape character is the default.

We can explore these more with the example below.

we have employee_addresses.txt file:

name,address,date joined
Raam,Lajpat nagar New Delhi, 11024, Jan 4
Satyam, Rohini New Delhi, 110085, March 2

This file is consisting of three fields which are name, address, date joined which are separated by commas.

The problem is here is that the address field data is also containing the comma to specify the zip code.

Here, three different ways are possible to overcome this problem:

by using different delimiter:

We can safely use the comma in the data itself by using the different delimiter. we can use the delimiter additional parameter to define the new delimiter.

wrapping the data in quotes:

Here, the quotechar optional parameter can be used to define that the character used for quoting. whereas that character also does not show in the data, everything is fine.

by escaping the delimiter character:

Escape characters work as same as do in format strings and it invalidates the definition of the character being escaped and this is for delimiter character.
escapechar must specify the escape character when it is used.

Writing the CSV file:

The writing of csv file can be done by using .write_row() method and a writer object.

import csv

with open('employee_file.csv', mode='w') as employee_file:

    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['Raam', 'Accounting', 'November'])

    employee_writer.writerow(['Aakash', 'IT', 'March'])

Here, while writing which character is to be used is specified by the quotechar optional character.

It returns the plaintext which shows that the file is created for reading.


Raam, Accounting, November

Aakash,IT, March

Writing of CSV file from the dictionary:

As we can read the data from the dictionary. also, we can write the data from the dictionary as well.

import csv

with open('employee_file2.csv', mode='w') as csv_file:

    fieldnames = ['emp_name', 'dept', 'birth_joining']

    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)


    writer.writerow({'emp_name': 'Raam', 'dept': 'Accounting', 'joining_month': 'November'})

    writer.writerow({'emp_name': 'Aakash', 'dept': 'IT', 'joining_month': 'March'})

While writing a dictionary the fieldnames parameter is required.




Aakash,IT, March

Handling CSV files by using Pandas library:

Pandas is the most popular Data science library in Python. It is used for data analysis and data manipulation.

When the amount of data is large it is better to use the Pandas library to handle the CSV files.

we have to install the Pandas before using them and to

know about installation visit: How to install Pandas?

Reading CSV File by using Pandas:

The read_csv() function is employed for reading the CSV files using Pandas.


import pandas as pd


This code reads the employee.csv from the current directory.

Writing CSV files by using Pandas:

The to_csv() function is employed for writing to the CSV files using Pandas. The to_csv() is DatafFrame's function.


import pandas as pd

# creating a data frame

df = pd.DataFrame([['Raam', 24], ['Aakash', 22]], columns = ['Name', 'Age'])

# writing data frame to a CSV file


Here the DataFrame is created by using pd.Dataframe and then to_csv() function is called for this object.


Name, Age

Raam, 24

Aakash, 22


In this article, we have discussed about the Python CSV module and understood how to perform different operations for reading and write data in CSV Files.