CSV FILES Online

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

CSV FILES

COMMA SEPARATED VALUES


CSV FILES
• CSV is a simple file format used to store tabular data, such as a
spreadsheet or database.
• They mostly use the comma character to separate data, but
sometimes use other characters, like semicolons.
• You can also open CSV files in spreadsheet programs, which make
them easier to read.
• The basic format is defined by a rows of column data.
• Each row is terminated by a newline to begin the next row.
• Within the row each column is distinguished by a comma.
• You can just double-click a .csv file to open it in Excel by default.
• CSV file format is mainly used by Data Scientist for Visualization.
CSV FILES

• For working with CSV files in python, there is


an inbuilt module called csv.
• The csv module’s reader and writer objects read
and write sequences.
CSV FILES
W
r
i
t c
i s
n v
g
f
t i
o l
e
t
h
e
W
r
i
t c Alternatively,
populate the list first
i s and then use loop
n v with writerow()
function to send the
g data to the csv file
f
t i
o l
e
t
h
e
W
r
i
t c
i s
n v
g
f
t i
o l Though I have not given
e delimiter argument with writer()
function, its taking it as
t comma(,) by default
h
e
W
r
i
t c
i s
n v
g
f
t i
o l Note: the
change of
e delimiter
t
h
e
W
r
i
t c
i s
n v
g
f
t i
o l
e
t
h
e
W Use of writerows() function
r
i
t c
i s
n v
g
f
t i
o l
e
t
h
e
Use of reader() function to read whole data in one go
r t
e h
a e def read_data():
d with open("f1.csv",'r') as fobj:
i c #reader() function reads the file object
n s #csv_r is the csv reader object
g v csv_r=csv.reader(fobj)
for record in csv_r:
f f print(record)
r i
o l
m e
import csv nm=input("enter print(record)
name")
d def write_data(): cl=input("enter class") #driver code
C
r yr=input("enter year") while True:
o fields=['NAME','CLASS','YEAR' pr=input("enter print("1: write data")
i
m ,'PERCENT'] percentage") print("2: display all")
v with L=[nm,cl,yr,pr] print("0: exit")
p
e open("f1.csv",'w',newline='') csv_w.writerow(L) ch=int(input("enter
l as fobj: print("File created") choice"))
n
e if ch==1:
t csv_w=csv.writer(fobj,delimit def read_data(): write_data()
p er=',') with open("f1.csv",'r') as elif ch==2:
e
r csv_w.writerow(fields) fobj: read_data()
o #reader() function reads elif ch==0:
m num_of_rec=int(input("How the file object break
g many records do u want to #csv_r is the csv reader
e
r enter")) object
n for i in csv_r=csv.reader(fobj)
a
u range(num_of_rec): for record in csv_r:
m
r
c Use of reader() function to read whole data in one go AND STORE DATA IN A LIST
e
s
a
v
d
i
f
n
i
g L
l
I
e
f S
r T
t
o
o
m

t
t
h
h
e
e
Source: geeksforgeeks

Not in syllabus

reader = csv.DictReader(open('coors.csv’))
dictobj = next(reader)
C F
O
O E
F
U T
N C
R
T H H
E The function next() is used to directly
I I E
C point to this list of fields to read the
N N A next line in the CSV file. next()
O
G G D method returns the current row and
R advances the iterator to the next row
E
D
N C R
S
U O S
M L
A
B U
N
E M
D
R N
U
S
E

The function seek() has placed the


O pointer after 20th byte from the
beginning. See the effect in the
F
output

S
E
E
K
()
A c
l o
t u
e n
r t
n i
a n
t g
e
r
w e
a c
y o
r
o d
f s
l
i
n
e
_
n
line_num is a counter which returns the number of rows which
u have been iterated
m

c
o
u
n
t
e
r
Updating record in csv file
[in this example increased marks of all students by 2]
Updating record in csv file
import csv print(rows)
with open("fname.csv",'w') as f:
Again
#writing to file wo=csv.writer(f,lineterminator='\n')
opening file
def write_data(): wo.writerows(rows) in writing
with open("fname.csv","a") as f: mode so
wo=csv.writer(f,lineterminator='\n') #driver code that
rec=['amit',1,34] while True: previous
wo.writerow(rec) print("1. write data") contents of
data=[['sumit',2,56.5],['charu',3,56],['mohit',4,57]] print("2. update marks") the file are
wo.writerows(data) print("0. exit") truncated
and
ch=int(input("enter choice"))
updated
def upd_rec1(): if ch==1:
records are
with open("fname.csv") as f: write_data() rewritten
ro=csv.reader(f) elif ch==2: back to the
rows=[] Reading data in a list upd_rec1() file
for rec in ro: elif ch==0:
rows.append(rec) break
for i in range(1,len(rows)):
Moving through each record to increase marks by 2
rows[i][2]=float(rows[i][2])+2
D Deleting record from csv file
E
L
E
T
E
N
R A
E M
C E
O
R
D

Record of charu deleted from file


B
Y
D import csv rows.append(rec)
E def del_rec(): print("records of file",f.name,"are:\n",rows)
with open("fname.csv") as f:
L
ro=csv.reader(f)
E A rows=[] Reading data in a list while True:
T N for rec in ro: print("1. write data")
E D rows.append(rec) print("2. update marks")
print("3. delete by name")
nm=input("Enter name whose record is to be deleted") print("4. display all")
R D
fields=['name','rno','marks'] print("0. exit")
E I with open("fname.csv",'w') as f:#will truncate all data ch=int(input("enter choice"))
C S of fname.csv and make the file blank if ch==1:
O P wo=csv.writer(f,lineterminator='\n') write_data()
R L wo.writerow(fields) elif ch==2:
D A for i in range(1,len(rows)): upd_rec1()
if(rows[i][0]==nm): If name matches, then don’t elif ch==3:
Y send that record to the file
pass del_rec()
B else: otherwise send the record elif ch==4:
Y A wo.writerow(rows[i]) fn=input("enter the name of the file whose record is
L to be displayed")
N L def display_all(fn): display_all(fn)
with open(fn) as f: elif ch==0:
A
ro=csv.reader(f) break
M rows=[]
E for rec in ro:
C import csv wo.writerows(rows) rows=[]
for rec in ro:
O #writing to file def del_rec(): rows.append(rec)
def write_data(): with open("fname.csv") as f: print("records of
M fields=['name','rno','marks'] ro=csv.reader(f) file",f.name,"are:\n",rows)
with open("fname.csv","a") as f: rows=[]
P wo=csv.writer(f,lineterminator='\n') for rec in ro: while True:
L wo.writerow(fields) rows.append(rec) print("1. write data")
rec=['amit',1,34] print("2. update marks")
E wo.writerow(rec) nm=input("Enter name whose record is print("3. delete by name")
to be deleted") print("4. display all")
T data=[['sumit',2,56.5],['charu',3,56],['mohit' fields=['name','rno','marks'] print("0. exit")
E ,4,57]] with open("fname.csv",'w') as f:#will ch=int(input("enter choice"))
wo.writerows(data) truncate all data of fname.csv and make the if ch==1:
file blank write_data()
def upd_rec1(): wo=csv.writer(f,lineterminator='\n') elif ch==2:
P with open("fname.csv") as f: wo.writerow(fields) upd_rec1()
R ro=csv.reader(f) for i in range(1,len(rows)): elif ch==3:
rows=[] if(rows[i][0]==nm): del_rec()
O for rec in ro: pass elif ch==4:
rows.append(rec) else: fn=input("enter the name of the file
G for i in range(1,len(rows)): wo.writerow(rows[i]) whose record is to be displayed")
rows[i][2]=float(rows[i][2])+2 display_all(fn)
R print(rows) def display_all(fn): elif ch==0:
A with open("fname.csv",'w') as f: with open(fn) as f: break
wo=csv.writer(f,lineterminator='\n') ro=csv.reader(f)
M
S i
e n
a
r c
c s
h v

b f
y i
l
n e
a
m
e
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
W
R
I
T
I
N
G
W
R
I
T
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G
S
E
A
R
C
H
I
N
G

int(i[3])>150
Write a program to calculate the sum of all the marks given in the file “marks.csv. Records in “marks.csv” are as
follows :
Rollno, Name, Marks
1, Suman, 67
2, Aman,71
C
3, Mini, 68
A 4, Amit, 80
L
C
U
L
A
T
I
N
G
Write a program to calculate the sum of all the marks given in the file “marks.csv. Records in “marks.csv” are as
follows :
Rollno, Name, Marks
1, Suman, 67
2, Aman,71
C
3, Mini, 68
A 4, Amit, 80
L
C
def calc():
U import csv
L f=open("marks.csv","r")
A ro=csv.reader(f)
T next(f)
I s=0
N for rec in ro:
s=s + int(i[2])
G
print("Total Marks are " ,s)
f.close( )
C Write a program to copy all those records from product.csv to
o high_price.csv whose price is more than 300. Format of record
p stored in product.csv is product id, product name, price. Display
y
the records of high_price.csv
i
n
g f
i
t l
o e

o
t
h
e
r
C def copy_data():
o import csv
Write a program to copy all fr=open("product.csv" , "r")
p
those records from ro=csv.reader(fr)
y
product.csv to high_price.csv fw=open(“high_price.csv”,’w’)
i wo=csv.writer(fw)
whose price is more than
n headers=next(f)
300. Format of record stored
g f wo.writerow(headers)
in product.csv is product id, for rec in ro:
i
product name, price. Display if int(rec[2])>300:
t l
the records of high_price.csv wo.writerow(rec)
o e
fr.close( )
fw.close()
o print("product whose price is more than 300")
t fr=open("product.csv" , "r")
h ro=csv.reader(fr)
e for rec in ro:
r print(rec)
Write a program to copy all those records from product.csv to
C
o
high_price.csv whose price is more than 300. Format of record stored in
p
product.csv is product id, product name, price. Display the records of
y high_price.csv OR
i
def product():
n with open("product1.csv", "r") as f1, open("high_price.csv","w+",newline='') as f2:
g f ro=csv.reader(f1)
i wo=csv.writer(f2)
t l reclist=[]
o e for rec in ro:
if int(rec[2])>300:
reclist+=[rec]
o
wo.writerows(reclist)
t
f2.seek(0)
h ro_f2=csv.reader(f2)
e for rec in ro_f2:
r print(rec)
C
o Write a program to count number of records present in
u “data.csv” file.
n
t
i
n
g

r
e
c
o
r
d
s
C
o Write a function count_rec(fname) to count and return number
u of records present in “data.csv” file. File has headers too.
n
t def count_rec(fname):
i import csv
n f = open(fname , "r")
g ro = csv.reader(f)
next(ro) #to skip header row
r r=0
e for row in ro:
c r = r+1
o print("Number of records are " , r)
r
d
s
Write a function UPD_RENT to increase the rent by 5% of those
tenants whose tenure of stay is more than 1 year in the file
tenant.csv. Function should return the number of records
U
updated. File has the data [TID,TNAME,RENT,TENURE_OF_STAY]
p
r
d
e
a
c
t
o
e
r
d
f
s
e
w
Write a function UPD_RENT to increase the rent by 5% of those tenants whose tenure
of stay is more than 1 year in the file tenant.csv. Function should return the number of
records updated. File has the data [TID,TNAME,RENT,TENURE_OF_STAY] with headers
U def UPD_RENT(): inc=int(row[2])*0.05
p
r
import csv row[2]=int(row[2])+inc
d
e
f = open("TENANT.CSV" , "r") r = r+1
a ro = csv.reader(f) f.close()
c
t fields=next(ro) #to skip header if r!=0:
o
e row f = open("TENANT.CSV" , "w")
r
d rows=[] wo = csv.writer(f)
f for rec in ro: wo.writerow(fields)
s
e rows.append(rec) wo.writerows(rows)
w r=0 print("file updated")
for row in rows: return r
if int(row[3])>1:
Write a function DEL_REC()
to delete records of those
tenants whose tenure of
stay is less than 1 year from
the file tenant.csv. File has
the data
[TID,TNAME,RENT,TENURE_
OF_STAY]
def DEL_REC():
import csv
f1 = open("TENANT.CSV" , "r")
ro = csv.reader(f1)
Write a function DEL_REC()
fields=next(ro) #to skip header row
to delete records of those rows=[]
tenants whose tenure of for rec in ro:
rows.append(rec)
stay is less than 1 year from
f1.close()
the file tenant.csv. File has f1=open("TENANT.CSV" , "w“,newline=‘’)
the data wo = csv.writer(f1)
wo.writerow(fields)
[TID,TNAME,RENT,TENURE_
for row in rows:
OF_STAY] if int(row[3])>=1:
wo.writerow(row)
print("file updated")
DEL_REC()
C. csv

You might also like