0% found this document useful (0 votes)
8 views4 pages

12 -CS - CSV File

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 4

12.

CSV FILE

CSV stands for Comma Separated values.


e.g.
rno, name, marks
Rno Name Marks
11, Kush, 55 11 Kush 55
12, Abhijeet, 59 12 Abhijeet 59

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.

csv file is used to store tabular data in a comma separated values.


Each line of file is a data record
Each record consists of one or more field separated by comma. (comma is separator). Comma is
also a delimiter which separates two files in a row

csv module is used to perform read/ write operation in csv

file. import csv module # import csv


csv.reader( ) # Read from csv file
csv.writerow( ) # Write to csv file – single row
csv.writerows( ) # Write to csv file – multiple rows
open( ) # Functions to open csv file
close( ) # Functions to close csv file

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

OPEN CSV FILE


There are two ways to open a csv file
a. file variable/ file handler = open(csv_file_name, access_mode)
b. using with function
with open( csv_file_name, access_mode) as file variable/ file handler :

CLOSE CSV FILE


file variable/ file handler.close( )

#working with csv files


import csv
f = open("myfile.csv", "r")
rec = csv.reader(f)

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


To write csv file in python, we can use csv.writer() function.
The csv.writer() function returns a writer object that converts the user’s data into delimiter string.
The string can later be used to write into CSV File using writerow( ) function.

#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()

WRITE MULTIPLE ROWS WITH WRITEROWS( ) FUNCTION


If we need to write the content of 2‐Dimensional list into csv file, instead of using writerow( )
function many times, we can write writerows() function.

#writing Multiple records to csv file


import csv
L = (["Rno", "Sname", "marks"],
["301", "Anamika", "40" ],
["302", "Kanika", "50" ],
["303", "Bhumika", "60" ])
with open("myfile3.csv", "w", newline='') as fw:
wrec = csv.writer(fw)
wrec.writerows(L)
print("\nMultiple rows sucessfully written")
fw.close()

CONTENT OF CSV FILE : MYFILE3.CSV

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”

#Append data to csv


file import csv
Fa =open("myfile3.csv", "a", newline=''):
wrec = csv.writer(fw)
wrec.writerow(["207", "Akash", "99" ])
print("\ndata sucessfully Appended")
fw.close()

Before Append After append

APPEND DATA TO CSV FILE FROM USER


Append data means, previous data will exists. After all previous data, new data will be inserted
after last record. ACCESS MODE will be “a”
Record will be given by user when program is run and will be added to csv file.

#Append data to csv


file import csv
Fu =open("myfile3.csv", "a", newline='')
w = csv.writer(Fu)
N = int(input("Enter no of record to add :
")) for x in range(N):
rn = int(input("Enter rollno :
")) nm = input("Enter Name :
")
mrk = int(input("Enter Marks :
")) L = [rn, nm, mrk]
w.writerow(L)
print("\nRow sucessfully Added")
print("\nAll rows are added")
Fu.close()

OUTPUT CSV FILE

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()

**************
*

You might also like