12 -CS - CSV File
12 -CS - CSV File
12 -CS - CSV File
CSV FILE
A CSV (Comma Sepparated Value) format is one of the simplest and common way to store tabular
data. To represent a csv file, it must be saved with .csv extension.
ACCESS MODE
r ‐ read mode used to read the content of csv
file. w ‐ write mode used to write to
csv file,
previous data is first deleted and write new data.
Only newly added data will be shown to csv file.
a ‐ append mode data will be added at the last
previous data is not deleted, only inserted after previous data
for r in
rec:
print(r)
f.close()
1
READING CSV FILE
The csvreader( ) function is used to read the file, which returns an iterable reader object.
The reader object is then iterated using for loop to print the content of each row.
csv.reader() function in default mode of csv file having comma delimiter.
If our csv file is a tab delimiter, to read such files, we need to pass optional parameter to
csv.reader( ) fnction.
f = open("myfile.csv", "r", “\t”) f = open(csvfile, mode,delimiter)
f = open("myfile.csv", "r", “,”)
#writing to csv
file import csv
with open("myfile2.csv", "w", newline='') as fw:
wrec = csv.writer(fw)
wrec.writerow(["Rno", "Sname", "marks" ])
wrec.writerow(["201", "Shruti", "62" ])
wrec.writerow(["202", "Monika", "76" ])
wrec.writerow(["203", "Aditi", "83" ])
print("\ndata sucessfully written")
fw.close()
2
APPEND DATA TO CSV FILE
Append data means, previous data will exists. After all previous data, new data will be inserted
after last record. ACCESS MODE will be “a”
3
SINGLE FILE TO FIRST CREATE FILE USING WRITE AND THEN READ RECORD
#Read and write in a single csv
file import csv
F = open("item.csv", "w", newline ='')
W = csv.writer(F)
N = int(input("No. of records to enter : "))
for i in range(N):
ino = int(input("Enter Item No. : "))
iname= input("Enter Item Name : ")
iprice = int(input("Enter Item Price :
")) L = [ino, iname, iprice]
W.writerow(L)
print("Records successfully added\n")
F.close()
F = open("item.csv","r")
rec = csv.reader(F)
print("\nRecords in file")
for i in rec:
print(i)
F.close()
OUTPUT
APPEND RECORD
#append data from user in csv
file import csv
F = open("item.csv", "a", newline ='')
W = csv.writer(F)
N = int(input("No. of records to enter : "))
for i in range(N):
ino = int(input("Enter Item No. : "))
iname= input("Enter Item Name : ")
iprice = int(input("Enter Item Price :
")) L = [ino, iname, iprice]
W.writerow(L)
print("Records successfully added\n")
F.close()
**************
*