How to use python csv module

Namaste Friends,




Friends, many times we needs to export or import data from spread sheet or any other database that is not belongs to our system. These  exports or imports are mostly based on comma-separated-value format. As you can also see, python csv module also called comma-separated module.


Q 1. What is python csv module?

Ans. Python CSV module provides us ability to read,write and access our data in comma-separated value format. Mostly This Format are used by many database, spreadsheets and other data storage appications to share, transfer or store in human readable form. A Normal human being can also read CSV module recorded data.

Q 2. How CSV module Works?

Ans. This Module has ability to read,write and access data from comma separated value format where all data values are stored in human readable form. This module provides us a very simple interface to interact with CSV module. Its Interface is very easy to read data from file row by row.


Python CSV Module Tutorial With Example.  



Input : [1]  


#
# ==================================================
#          PYTHON csv MODULE TUTORIAL
# ==================================================
# 
# author   : suraj singh bisht
# contact  : SSB
#            surajsinghbisht054@gmail.com
#            https://bitforestinfo.blogspot.com
#            
# Here, For This Tutorial
#
# I am using
#
# Operating System : Ubuntu 16.04
# Python Version   : python 2.7.12
# Editor           : ipython notebook
#

Output : [1]  

  

Input : [2]  

#
# import module
#
import csv

Output : [2]  

  

Input : [3]  

# 
# Choose any filename for csv.
#
csv_file = "csv_Example_file.csv"

Output : [3]  

  

Input : [4]  

#
# In this Example, i will show you usage of csv.writer
# function. This Function Provide us writing capability.
# To use this Function, we need a file object for storing data
#
# Open File Object
f_open = open(csv_file, 'w')
#
# open csv.writer object handler
w = csv.writer(f_open)

Output : [4]  

  

Input : [5]  

#
# Writing First Row
w.writerow(["ROW NO.", "SQUARE", "CUBE"])
#
# Wrting Many Rows
for i in range(10):
    w.writerow(["Row : ".format(i),i**2,i**3])
#
#

Output : [5]  

  

Input : [6]  

# 
# Close Open File Object Handler
f_open.close()

Output : [6]  

  

Input : [7]  

#
# Now, Let's See How csv.writer Saves our data in normal
# Txt Files.
#
print open(csv_file,'r').read()

Output : [7]  

"ROW NO.","SQUARE","CUBE"
"Row : ","0","0"
"Row : ","1","1"
"Row : ","4","8"
"Row : ","9","27"
"Row : ","16","64"
"Row : ","25","125"
"Row : ","36","216"
"Row : ","49","343"
"Row : ","64","512"
"Row : ","81","729"

Input : [8]  

# As you can see above, csv.writer saved data in normal form
# but for reading data from csv file we needs another function
# called csv reader
# Even For This Function, we needs file object.
#
# Create File Object Handler
f_open = open(csv_file,'r')
#
# Create csv.reader object
r = csv.reader(f_open)
#
# iter all rows from csv.reader
for row in r:
    # print each row
    print row
    

Output : [8]  

['ROW NO.', 'SQUARE', 'CUBE']
['Row : ', '0', '0']
['Row : ', '1', '1']
['Row : ', '4', '8']
['Row : ', '9', '27']
['Row : ', '16', '64']
['Row : ', '25', '125']
['Row : ', '36', '216']
['Row : ', '49', '343']
['Row : ', '64', '512']
['Row : ', '81', '729']

Input : [9]  

#
# In this Example, we will see example of csv Quoting.
# Quoting is a like selecting different quote settings
# to write data with sepecified quotes configuration
# available in csv python module.
#
# Open File Object in write mode
f_open = open(csv_file, 'w')
#
# apply any one quotes options from several quotes options
# available in csv.
#
w = csv.writer(f_open, quoting=csv.QUOTE_ALL)
#
# write First Row
w.writerow(["ROW NO.", "SQUARE", "CUBE"])
#
# write other rows
for i in range(10):
    w.writerow(["Row : ".format(i),i**2,i**3])
#
# Close File Handler
#   
f_open.close()
#
# Now, again open saved csv file and compare with previous example
#
print open(csv_file,'r').read()

Output : [9]  

"ROW NO.","SQUARE","CUBE"
"Row : ","0","0"
"Row : ","1","1"
"Row : ","4","8"
"Row : ","9","27"
"Row : ","16","64"
"Row : ","25","125"
"Row : ","36","216"
"Row : ","49","343"
"Row : ","64","512"
"Row : ","81","729"

Input : [10]  

#
# csv writer Quoting options will not effect
# Read Data Procedure From csv file. 
#
# As you Can See, Completely Same
#
f_open = open(csv_file,'r')


r = csv.reader(f_open)

for row in r:
    print row
    
    

Output : [10]  

['ROW NO.', 'SQUARE', 'CUBE']
['Row : ', '0', '0']
['Row : ', '1', '1']
['Row : ', '4', '8']
['Row : ', '9', '27']
['Row : ', '16', '64']
['Row : ', '25', '125']
['Row : ', '36', '216']
['Row : ', '49', '343']
['Row : ', '64', '512']
['Row : ', '81', '729']

Input : [11]  

#
# In this Example, I will demonstrate csv.DictWriter.
# csv.DictWriter provides us new feature for writing 
# data like Dictonery Object.
#
# As usaul, open file object
f_open = open(csv_file, 'w')
# 
# Create Dictwriter object and also provide total Dictonery key lists
#
w = csv.DictWriter(f_open, fieldnames=["Row No.","Square ","Cube   "])
#
# now, write dict key header in file
#
w.writeheader()
#
# Write all data in dictonery form
#
for i in range(10):
    w.writerow({"Row No." :i,
                "Square " :i**2,
                "Cube   " :i**3})
#
# Close File handler
#
f_open.close()

Output : [11]  

  

Input : [12]  

#
# And at the end, we will use DictReader for reading
# DictWriter Written Data From Csv File.
# And For This First,
#
# Open File Object
f_open = open(csv_file,'r')
#
# Create csv DictReader Object
r = csv.DictReader(f_open)
#
# iter all data
for row in r:
    # print Dict
    print row
    
#
# Close file object
f_open.close()

Output : [12]  

{'Square ': '0', 'Row No.': '0', 'Cube   ': '0'}
{'Square ': '1', 'Row No.': '1', 'Cube   ': '1'}
{'Square ': '4', 'Row No.': '2', 'Cube   ': '8'}
{'Square ': '9', 'Row No.': '3', 'Cube   ': '27'}
{'Square ': '16', 'Row No.': '4', 'Cube   ': '64'}
{'Square ': '25', 'Row No.': '5', 'Cube   ': '125'}
{'Square ': '36', 'Row No.': '6', 'Cube   ': '216'}
{'Square ': '49', 'Row No.': '7', 'Cube   ': '343'}
{'Square ': '64', 'Row No.': '8', 'Cube   ': '512'}
{'Square ': '81', 'Row No.': '9', 'Cube   ': '729'}


Hence, This tutorial Ends Here.

Some Useful links for you.

Sqlorm (sqlite3 Object Relational Mapper)

Shelve Tutorial
whichdb Tutorial


if you like my tutorial,
then like, comment, share
and follow us.


Written By
             SSB

Share this

Related Posts

Previous
Next Post »