CSV_File_Handling
CSV_File_Handling
A CSV file (Comma Separated Values file) is a type of plain text file that uses
specific structuring to arrange tabular data.
Normally, CSV files use a comma to separate each specific data value.
and so on ...
The separator character is called a delimiter, the comma is not the only one used.
Other popular delimiters include the tab (\t), colon (:) and semi-colon (;).
Each line in a CSV file is known as a record. Each record consists of one or more
fields or columns, separated by comma(default).
• It is compact.
• It is simple to implement
2.Reading from CSV file – reading from a csv file is done using reader object.
This object is created using the reader() or DictReader() function of csv
module. Reader object is an iterable that gives us access to each line of the
csv file as list of fields. One can traverse the whole file using reader object with
for loop. next() function can also be used to read the file. It returns the
current row and advances the iterator to the next row.
3. Writing to the CSV file – for writing to a csv file, writer() or DictWriter()
function of csv module is used. These functions return a writer object that use
writerow() or writerows() method for writing iterable objects like list,
dictionary to the file.
Note –reader() and writer() functions are generally used when list type of
data is to be read/ written from/to the file. DictReader() and DictWriter() is
used when dictionary data is to be read/written from/to the file .
Example 1 – A function to one record at a time write in a CSV file.
def writecsv() :
# opening a fie in write mode
f = open("csvfile","w")
# creating a writer object
cobj = csv.writer(f)
# defining the columns or fields of a record
field = ["roll","name","marks"]
# writing a row in the file
cobj.writerow(field)
while True :
r = int(input("Enter roll no "))
n = input("Enter name ")
m = int(input("Enter marks "))
rec= [r,n,m]
# writing a row in the file
cobj.writerow(rec)
ans = input("Continue? ")
if ans.upper() == 'N' :
break
f.close()
def display() :
# opening a file in read mode
f = open("csvfile","r")
# creating a reader object
cobj = csv.reader(f)
#read the current row and place the iterator to the next row
field = next(cobj)
#printind the first row which is the heading
print(field)
for row in cobj :
print (row)
f.close()
Output –
[]
def display_csv() :
# opening a file in read mode
f = open("csvfile","r")
# creating a reader object
cobj = csv.reader(f)
#read the current row and place the iterator to the next row
field = next(cobj)
#printing the first row which is the heading
print(field)
for row in cobj :
print (",".join(row)) The join() method provides a flexible way to
f.close() create strings from iterable objects. It joins
each element of an iterable (such as list, string,
Output – and tuple) by a string separator and returns
the concatenated string.
31,Neeraj,58
Syntax: string separtor.join(iterable object)
32,Gaurav,84 Here “,” is the string separator and row is the
iterable object.
33,Harsha,60
def search(name) :
with open("csvfile","r") as f : close() is not required if with statement is
# creating a reader objrct used for opening a file
cobj = csv.reader(f)
found = 0
After every row there is a blank row. See the
for row in cobj : output of example 2. If file is opened with new
if row != [] : line disabled then this statement is not required.
if row[1] == name :
found = 1
Object “row” is a list. Here index no. 0 has roll
break no, index no 1 has name and index no 3 has
marks
if found == 0 :
Output –
Enter the name to be searched Harsha
Roll no : 33 Marks : 60
Example 5 – A function to write all the records in the CSV file at one go.
def write_csv() :
# opening a fie in write mode and disabling newline
f = open("csvfile","w", newline=’’)
# creating a writer object
cobj = csv.writer(f)
# defining the columns or fields of a record
field = ["roll","name","marks"]
# writing a row in the file
cobj.writerow(field)
# creating a list object
rec = []
while True :
r = int(input("Enter roll no "))
n = input("Enter name ")
m = int(input("Enter marks "))
data = [r,n,m]
# appending the given record in the list
rec.append(data)
ans = input("Continue? ")
if ans.upper() == 'N':
break
# writing a row in the file
cobj.writerow(rec)
f.close()
Example 6 – A function to update marks.
def update():
f = open("exam.csv","r+")
roll = input("Enter roll no to be updated ")
cobj = csv.reader(f)
rows = []
found = 0
for rec in cobj :
# searching record ist element in the list I is roll no
if roll == rec[0] :
# input modified data
marks = input("Enter marks ")
found = 1
# modifying marks in the list
rec[2] = marks
# adding each record to the list
rows.append(rec)
f.close()
if found == 1:
f = open("exam.csv", "w", newline = '')
#creating a writer object
csw = csv.writer(f)
#writing all the rows
csw.writerows(rows)
f.close()
else:
print(roll,"not found")
def del_rec_1():
f = open("exam.csv","r")
f1 = open("temp.csv","w",newline='')
roll = input("Enter roll no whose record is to be deleted ")
csr = csv.reader(f)
csw = csv.writer(f1)
for rec in csr:
#searching for the roll no.
if roll != rec[0]:
# writing records to temp file if roll no is not found
csw.writerow(rec)
f.close()
f1.close()
os.remove("exam.csv")
os.rename("temp.csv", "exam.csv")
def csv_dict() :
# opening a fie in write mode
f = open("exam_dict.csv","w",newline='')
# defining the columns or fields of a record
field = ["Roll","Name","Marks"]
# creating a writer object and specifying the field names
cobj = csv.DictWriter(f, fieldnames = field)
# writing the field names in the file
cobj.writeheader()
while True :
r = int(input("Enter roll no "))
n = input("Enter name ")
m = int(input("Enter marks "))
dict= {}
dict = {"Roll":r,"Name":n,"Marks":m}
# writing a row in the file
cobj.writerow(dict)
ans = input("Continue? ")
if ans.upper() == 'N' :
break
f.close()
Output –
45 Ashish 75
46 Shashi 73
47 Chandan 74
import csv
import os
writecsv()
write_csv()
display()
display_csv()
nm = input("Enter the name to be searched ")
search(nm)
update_1()
update_2()
del_rec_1()
display_csv()
csv_dict()
display_dict()
Lab Assignment:
1. Write a menu driven program to add, display, search and update in a
csv file containing city, active cases, recovered, deaths, date. Use list data
to store in csv file. Search on the basis of city and date. Update on the basis
of city and date.
2.Write a program to add and display in a csv file containing dictionary
data. Each record contains item no, item name, unit price, qty.