Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

CSV_File_Handling

Uploaded by

bhavinx15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

CSV_File_Handling

Uploaded by

bhavinx15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CSV files

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.

Format of a CSV file:

column 1, column 2, column 3

first row data 1, first row data 2, first row data 3

second row data 1, second row data 2, second row data 3

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).

Advantages of CSV file:

• CSV is processed by almost all existing applications.

• It is compact.

• It is easier to generate and import onto a spreadsheet or database.

• It is human readable and easy to edit manually.

• It is simple to implement

Operations on a CSV file

1. Opening the file – same as opening a text file using open().

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.

4. Closing the file – use close() method

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()

Example 2 – A function to read from a CSV file.

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 –

['roll', 'name', 'marks']

[] The way Python handles newlines in CSV


files can result in blank lines appearing
['31', 'Neeraj', '58']
between rows when using csv.writer.
[]
In Python 3, while opening the CSV file in
['32', 'Gaurav', '84'] writing mode, disable universal newlines.

[] f = open ('csvfile', 'w', newline='')


['33', 'Harsha', '60']

[]

Example 3 -A function to display records in CSV format.

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

Example 4 -A function to search a record in a CSV file.

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 :

print("Roll no :", row[0],"Marks :",row[2])

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 :

print(name, " not found")

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")

Example 7 – A function to update marks by copying records to


another file.
def update_2():
f = open("exam.csv","r")
f1 = open("temp.csv","w",newline='')
roll = input("Enter roll no whose marks is to be updated ")
csr = csv.reader(f)
csw = csv.writer(f1)
found = 0
for rec in csr:
#searching record
if roll == rec[0]:
marks = input("Enter the changed marks ")
found = 1
# modifying marks in the list
rec[2] = marks
# writing records to temp file
csw.writerow(rec)
# close the files before deleting and renaming files
f.close()
f1.close() Both the remove() and
# deleting the exam.csv file rename() methods are
os.remove("exam.csv") in os module which has
# renaming the temp.csv file as exam.csv to be imported before
os.rename("temp.csv", "exam.csv") they are executed.
if found == 0 :
print(roll,"not found")

Example 8 – A function to delete a record from a file by copying


records to another file.

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")

Example 9 – A function to delete a record from a file.

# deleting record by copying all the records in a list first


def del_rec_2() :
f = open("exam.csv","r+")
roll = input("Enter roll no whose record is to be deleted ")
cobj = csv.reader(f)
rows = []
found = 0
for rec in cobj :
# searching the roll no
if roll != rec[0] :
# appending record in rows object if roll no is not found
rows.append(rec)
f.close()
f = open("exam.csv", "w", newline = '')
#creating a writer object
csw = csv.writer(f)
#writing all the rows
csw.writerows(rows)
f.close()

Example 10 – A function to create a CSV file with help of a


dictionary.

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()

Example 11 – A function to display records from a CSV file with


help of a dictionary.

# displaying records from a CSV file with help of dictionary


def display_dict():
f = open("exam_dict.csv", "r")
#creating a reader object
csd = csv.DictReader(f)
# iterating reader object for file data
for rec in csd :
print(rec["Roll"],rec["Name"],rec["Marks"])
f.close()

Output –

45 Ashish 75
46 Shashi 73
47 Chandan 74

Invoking all the functions

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.

You might also like