0% found this document useful (0 votes)
24 views

CSV File Handling

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

CSV File Handling

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

CSV FILES

CSV – COMMA SEPARATED VALUE FILE


Extension of the file- .csv

A comma-separated values file is a text file that uses a comma to separate values. Each line
of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file
format.
Advantages:
CSV file stores data as text and can handle large amount of data.
Data is stored in a tabular form (rows and columns).
It is easy to export from data base and spread sheet software like Excel. It is easy to
import data from a csv file to a data base and spread sheet software.
CSV files are supported by nearly all data upload interfaces. If you are planning to
move your data between platforms, export and import it from one interface to another,
you might be better off with the CSV file format.

In CSV file, text data is in a format where each line is considered as a row/record with many fields.
Fields are separated by a delimiter like , or / or – etc.
The first line generally contains the header of the fields
DATA IN EXCEL FILE or DATA IN A CSV FILE
DATABASE TABLE
Writing in CSV files

• Csv module is used to read/write in a csv file

• Csv.writer() function to convert file object into writer object

• Csv.writerow() function to insert records in the csv file


• (records will be in the form of lists)
import csv import csv
def write_data(): def write_data():
f=open("classxii.csv","w") f=open("classxii.csv","w“, newline=“\n”)
OR
w=csv.writer(f,delimiter=',',lineterminator='\n') w=csv.writer(f,delimiter=',')
w.writerow(["AdmnNo","Name","Age"]) w.writerow(["AdmnNo","Name","Age"])
n=int(input("How many records: ")) n=int(input("How many records: "))
for i in range(n): for i in range(n):
adm=input("Enter admission number: ") adm=input("Enter admission number: ")
nm=input("Enter name: ") nm=input("Enter name: ")
age=int(input("Enter age: ")) age=int(input("Enter age: "))
rec=[adm,nm,age] rec=[adm,nm,age]
w.writerow(rec) w.writerow(rec)
f.close() f.close()

write_data() write_data()
Reading CSV files

• Csv module is used to read/write in a csv file

• Csv.reader() function is used to read records from the


file

• The records are in the form of list of list


import csv
Reading, Writing, Searching
def write_data(): def search_data():
f=open("d.csv","w") f=open("d.csv","r")
w=csv.writer(f,delimiter=',',lineterminator='\n') rec=csv.reader(f)
w.writerow(["AdmnNo","Name","Age"]) #print(rec)
n=int(input("How many records: ")) next(rec)
for i in range(n): for i in rec:
adm=input("Enter admission number: ") if i[1][0]=="u" or i[1][0]=="U":
nm=input("Enter name: ") print(i)
age=int(input("Enter age: ")) f.close()
rec=[adm,nm,age]
w.writerow(rec)
f.close() write_data()
print("*****reading data*****")
def read_data(): read_data()
f=open("d.csv","r") print("*****searching data*****")
rec=csv.reader(f) search_data()
#print(rec)
for i in rec:
print(i)
f.close()
A CSV file “country.csv” contains
<country>,<capital>

Display names of countries where capital is more than 6 characters long


import csv
def write_data():
f=open("country.csv","w")
w=csv.writer(f,delimiter=',',lineterminator='\n')
w.writerow(["Country","Capital"])
w.writerow(["INDIA","NEW DELHI"] )
w.writerow(["FRANCE","PARIS"] )
w.writerow(["US","WASHINGTON"] )

f.close()

def display():
f=open("country.csv","r")
rec=csv.reader(f)
print("Names of countries with more than 6 characters in
capital name")
next(rec)
for i in rec:
if len(i[1])>6:
print(i[0])
f.close()

write_data()
display()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>

Display details of products with the highest price


import csv #approach-1
def display_1():
def write_data(): f=open("product.csv","r")
f=open("product.csv","w") rec=csv.reader(f)
w=csv.writer(f,delimiter=',',lineterminator='\n') print("Details of products with maximum cost")
w.writerow(["Product Id", "Product name","Cost"]) next(rec)
w.writerow(["P1","TV", 20000] )
w.writerow(["P2","LAPTOP", 50000] ) Val=[]
w.writerow(["P3","WASHING MACHINE", 50000] ) for i in rec:
Val.append(int(i[2]))
f.close() m=max(Val)
f.seek(0)
next(rec)
print("Result")
for i in rec:
if int(i[2])==m:
print(i)

f.close()

Continued
#approach-2
def display_2():
f=open("product.csv","r")
rec=csv.reader(f)
print("Details of products with maximum cost")
next(rec)
max=0
for i in rec:
if int(i[2])>max:
max=int(i[2])

f.seek(0)
next(rec)
for i in rec:
if int(i[2])==max:
print(i)

f.close()

write_data()
display_1()
display_2()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to append record of type product to the csv file

def append_data():
f=open("product.csv","a")
w=csv.writer(f,delimiter=',',lineterminator='\n')
id=input("Enter product id: ")
nm=input("Enter product name: ")
cost=float(input("Enter cost of product: "))
data=[id,nm,cost]
w.writerow(data)
f.close()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to remove records on the basis of product name from the
csv file
def remove_data():
f=open("product.csv","r")
g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be deleted for: ")
rec=csv.reader(f)
header=next(rec)
w.writerow(header)
for i in rec:
if i[1]!=pn:
w.writerow(i)
f.close()
g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to update cost of product on the basis of product name
def update_data():
f=open("product.csv","r")
g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be updated: ")
rec=csv.reader(f)
header=next(rec)
w.writerow(header)

for i in rec:
if i[1]==pn:
i[2]=float(input("Enter updated cost: "))
w.writerow(i)
f.close()
g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
import csv MENU DRIVEN PROGRAM def display_data():
import os f=open("product.csv","r")
rec=csv.reader(f)
def write_data(): print("Data in the File")
f=open("product.csv","w") for i in rec:
w=csv.writer(f,delimiter=',',lineterminator='\n') print(i)
w.writerow(["Product Id", "Product name","Cost"])
w.writerow(["P1","TV", 20000] ) def search_data():
w.writerow(["P2","LAPTOP", 50000] ) f=open("product.csv","r")
w.writerow(["P3","WASHING MACHINE", 50000] ) rec=csv.reader(f)
flag=0
f.close() pn=input("Enter product name to be searched for: ")
for i in rec:
if i[1]==pn:
def append_data(): print(i)
f=open("product.csv","a") flag=1
w=csv.writer(f,delimiter=',',lineterminator='\n')
id=input("Enter product id: ") if flag==0:
nm=input("Enter product name: ") print("Unsuccessful search")
cost=float(input("Enter cost of product: ")) f.close()
data=[id,nm,cost]
w.writerow(data)
f.close()
MENU DRIVEN PROGRAM (Continued)

def remove_data(): def update_data():


f=open("product.csv","r") f=open("product.csv","r")
g=open("temp.csv","w") g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n') w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be deleted for: ") pn=input("Enter product name to be updated: ")
rec=csv.reader(f) rec=csv.reader(f)
header=next(rec) header=next(rec)
w.writerow(header) w.writerow(header)
for i in rec:
if i[1]!=pn: for i in rec:
w.writerow(i) if i[1]==pn:
f.close() i[2]=float(input("Enter updated cost: "))
g.close() w.writerow(i)
os.remove("product.csv") f.close()
os.rename("temp.csv","product.csv") g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
MENU DRIVEN PROGRAM (Continued)

write_data()
while(True):
print("Enter 1 to append, 2 to read, 3 to search, 4 to delete, 5 to update")
choice=int(input("Enter choice: "))
if choice==1:
append_data()
elif choice==2:
display_data()
elif choice==3:
search_data()
elif choice==4:
remove_data()
elif choice==5:
update_data()
else:
break
FOR FILE

A CSV file “book.csv” contains


<book id>,<book name>,<price>
Write a menu driven program to append, display, search (on basis of price
range), delete (on basis of book name), update (update price on basis of
book name)

You might also like