Working With CSV Files in Python
Working With CSV Files in Python
in python
CSV Files in Python - Import CSV, Open, Close csv, read-write csv using
csv.reader and csv.writerow article is mainly focused on CSV file operations
in Python using CSV module. This article helps to CBSE class 12 Computer
Science students for learning the concepts. So here we go!!
To import csv module you can use any one of the following syntax:
import csv
next() function: The next() function returns the next item in an iterator.
You can add a default return value, to return if the iterable has reached to its
end.
line_num this function is used to returns the number of rows that have
been iterated.
Creating header row and CSV file
When we are writing data into CSV file we have to create a header row
first. Follow the below given steps to write a header row.
Observe the following code which creates a CSV file and creates one object
to write a header row in CSV file. Here I have used writer() function to feed
data and writerow() function to insert values into a row.
import csv
f = open("DIS.csv","w")
ns = writer(f)
ns.writerow(['Rank','Batsman','Te','Rating'])
f.close()
You can insert single row or multiple rows together in CSV file. Let's have a
If you have already created a header row then you have to use append mode
to insert data. Observe the following code:
import csv
f =open("dis.csv","a")
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = nt(input("Enter rating:"))
dt = writer(f)
dt.writerow([r,b,t,rt])
print("Record has been added.") f.close()
f.close()
To insert multiple rows use while loop inside the function and use validation
to stop the input by the user. For validation, I have used a string variable to
check user want to restrict the data entry or want to continue. Observe the
following code I have done the
same.
Import csv
f = open("xiib.csv","a")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt.writerow([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = ch.upper()
if ch=="YES":
print("*************************")
else:
break
f.close()
Use of delimiter
When you need to store data which can be separated through any other
character except ,(comma) you can use delimiter parameter in writer()
/writerow() function. Write code like this where you have written writer()
/writerow() function:
dt = writer(f,delimiter="@")
When you write or use this method excel will display your data into single
column only.
Because CSV accepts only comma to separate values in excel.
Write a program in Python that defines and calls the following user defined
functions :
(i) Add_Teacher() : It accepts the values from the user and inserts record of
a teacher to a csv file ‘Teacher.csv’. Each record consists of a list with
field elements as T_id, Tname and desig to store teacher ID, teacher
name and designation respectively.
(ii) Search_Teacher() : To display the records of all the PGT (designation)
teachers.
import csv
def Add_Teacher():
dm=open("Teacher.csv","a",newline="\n")
T_id=int(input("Enter Teacher id: "))
Tname=input("Enter Teacher name: ")
desig=input("Enter Designation: ")
rec=[T_id,Tname,desig]
dp=csv.writer(dm)
dp.writerow(rec)
dm.close()
def Search_Teacher():
n=open("Teacher.csv",”r”)
ns=csv.reader(n)
for record in ns:
if record[2]=="PGT":
print(record)
n.close()
Add_Teacher()
Search_Teacher()
Roshni of class 12 is writing a program in Python for her project work to
create a csv file "Teachers.csv" which will contain information for every
teacher’s Identification Number, Name for some entries. She has written
the following code. However she is unable to figure out the correct
statements in a few lines of the code, hence she has left them blank.
Help her to write the statements correctly for the missing parts in the
code.
import _________ # Line 1
def addrec(Idno, Name): # to add record into the CSV file
f=open("Teachers.csv", _________) # Line 2
Filewriter = CSV.writer(f)
Filewriter.writerow([Idno,name])
f.close()
def readfile(): # to read the data from CSV file
f=open("Teachers.csv", ________) # Line 3
FileReader = CSV.________ (f) # Line 4
for row in FileReader:
print(row)
f._________ #Line 5
(a) Name the module she will import in Line 1.
Ans: csv as CSV OR csv
(b) In which mode will she open the file to add data into file in Line 2 ?
Ans: a OR a+ OR
(c) In which mode will she open the file to read the data from the file in
Line 3 ?
Ans: r OR r+ OR read (
(d) File in the blank in Line 4 to read the data from a CSV file.
Ans: reader
(e) Fill in the blank in Line 5 to close the file.
Ans: close()