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

CSV File

Uploaded by

mariamustafa404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CSV File

Uploaded by

mariamustafa404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

To write a single row

To write a many rows


To write a single row
Use the function
writerow()

To write a many rows


Use the function
writerows()

To display the content


use the function
reader()
Writing

Reading
Write a program to count the number of records present in ‘student.csv’ file

Note :The header of the student file will also gets counted.
write a python function searchcsv()to def searchcsv():
find only those records from the file
product.csv whose quantity is more
f=open("product.csv","r")
than 150. r=csv.reader(f)

sample of product.csv is given below: for i in r:


pid,pname,cost,quantity if i[3]> ‘150’:
p1,brush,50,200 print(i)
p2,toothbrush,120,150 f.close()
p3,comb,40,300
p4,sheets,100,500
searchcsv()
p5,pen,10,250
import csv
A csv file counties.csv contains data in the def searchcsv():
following order: country,capital,code f=open("counties.csv","r")
sample of counties.csv is given below: r=csv.reader(f)
INDIA, NEWDELHI,II f=0
US,WASHINGTON,UU for i in r:
MALAYSIA,KAUALAUMPUR,MM if (len(i[1])>6):
FRANCE,PARIS,FF print(i[0])
f+=1
write a python function to read the file
counties.csv and display the names of all if(f==0):
those countries whose no of characters in print("record not found")
the capital are more than 6.
searchcsv()
import csv
write a python function
def writecsv():
writecsv () to write the
f=open("product.csv","w",newline = "")
following information into
r=csv.writer(f)
product.csv.
r.writerow(['pid','pname','cost','qty'])
r.writerow(['p1','brush','50','200'])
pid,pname,cost,quantity
r.writerow(['p2','toothbrush','12','150'])
p1,brush,50,200
r.writerow(['p3','comb','40','300'])
p2,toothbrush,120,150
r.writerow(['p5','pen','10','250'])
p3,comb,40,300
f.close()
p4,sheets,100,500
p5,pen,10,250
writecsv()
write a python function
writecsv () to write the def writecsv():
following information f=open("product.csv","w",newline="")
into h=['pid','pname','cost','qty']
r=csv.DictWriter(f1,fieldnames=h)
product.csv. Using r.writeheader()
dictionary
v=[{'pid':'p1','pname':'brush','cost':'50','qty':'200'},
pid,pname,cost,quantity {'pid':'p2','pname':'toothbrush','cost':'12','qty':'150'},
p1,brush,50,200 {'pid':'p3','pname':'comb','cost':'40','qty':'300'},
p2,toothbrush,120,150 {'pid':'p5','pname':'pen','cost':'10','qty':'250'}]
p3,comb,40,300 r.writerows(v)
f.close()
p4,sheets,100,500
p5,pen,10,250

You might also like