CSV FILE
CSV (Comma Separated Values).
Each value is separated by delimiter
Extension of csv file is .CSV
If no delimiter is given default delimiter is comma(,)
Example of CSV FILE
1, Ashish ,20
2.Amod , 50
WRITING INTO CSV FILE
Writer():- returns object responsible for converting user data into delimited string
Writerow():- Used to write single list into file
Writerows():- Used for writing multiple rows into file
READING FROM CSV FILE
reader():- it is used to read from CSV file
It can iterates through line in specified CSV documents
A CSV file mobile.dat contains [model-no , company , price ]
Define following below mentioned functions
add( ):- To add record into CSV file mobile.csv.
count( ):- To count and display records from binary file mobile.csv
import csv
def add( ):
f=open('mobile.csv' , 'a' , newline='')
a=input('model')
b=input('company')
c=int(input('price'))
z=[a,b,c]
p=csv.writer(f , delimiter=',')
p.writerow(z)
f.close( )
def count( ):
f=open('mobile.csv' , 'r')
s=csv.reader(f)
c=0
for z in s:
print(z)
c=c+1
print(c)
f.close( )
add( )
count( )
A CSV file tv.csv contains [ model-no , company , price]
Define following below mentioned functions
add( ): :- To add content into CSV file tv.txt
display ( ) :- To display those records where price of tv is more then 5000
import csv
def add( ):
f=open('tv.csv' , 'a' , newline='')
a=input('model')
b=input('company')
c=int(input('price'))
z=[a,b,c]
p=csv.writer(f , delimiter=',')
p.writerow(z)
f.close( )
def display( ):
f=open('tv.csv' , 'r')
s=csv.reader(f)
c=0
for z in s:
if int ( z[2] ) > 5000:
print(z)
f.close( )
add( )
display( )
A CSV file holidays.csv contains [name , destination ,no of days , price ]
Define
insert( ):- To add record into CSV file ' holidays.dat'
show data( ): - To display and count those records where destination is Lucknow
import csv
def insert( ):
f=open('holidays.csv' , 'a' , newline='')
a=input('name')
b=input('destinstion')
c=input('no of days')
d=input('price')
z=[a,b,c,d]
w=csv.writer(f)
w.writerow( z)
f.close( )
def showdata( ):
f=open('holidays.csv' ,'r')
r=csv.reader(f )
c=0
for z in r:
if z[1]=='lucknow':
print(z)
c=c+1
print(c)
f.close( )
insert( )
showdata( )
A CSV file " Record.csv " contains [ Roll-No , Name , marks , grade]. Define
add( ):- To add record in file "Record.csv"
display( ):- To display those records where grade is "A" , "B" , "C"
import csv
def add( ):
f=open("Record.csv" , "a")
a=int(input("Roll"))
b=input("name")
c=int(input("marks"))
d=input("grade")
r=[a,b,c,d]
z=csv.writer(f)
z.writerow(r)
f.close( )
def display( ):
f=open("Record.csv" , "r")
s=csv.reader(f)
for z in s:
if z[3] in ["A" ,"B" , "C"]:
print(z)
f.close( )
add( )
display( )