CSV File Handling in Python
CSV File Handling in Python
Amit X A
Sumit XI B
Ashish XII C
If the values in the table contain comma(,) like below in column Address
Then in CSV it will be stored like below (Values containing comma will be enclosed in
double quotes)
Page 1 of 71
When do we use CSV file?
Ans.
When data has a strict tabular structure
To transfer large data between programs
To import and export data
Page 3 of 71
LF [ \ n ] Line Feed UNIX
CR / LF [ \ r \ n ] Carriage Return / Line Feed MS - DOS, Windows, OS/2
NULL [\0 ] Null character Other OSs
Now what would happen if you create a csv file on one operating system and use it on
another. The EOL of one operating system will not be treated as EOL on another operating
system. Also, if you have given a character , say ' \ r ' , in your text string ( not as EOL but as
part of a text string ) and if you try to open and read from this file on a Macintosh system ,
what would happen ? Mac OS will treat every ' \ r ' as EOL - yes, including the one you gave
as part of the text string. So what is the solution? Well, the solution is pretty simple. Just
suppress the EOL translation by specify third argument of open ( ) as newline = ' ' ( null
string - no space in quotes ).
ΝΟΤΕ: Additional optional argument as newline = ' ' (null string; no space in between) with
file open( ) will ensure that no translation of end of line (EOL) character takes place .
If you specify the newline argument while writing onto a csv file, it will create a csv file with
no EOL translation and you will be able to use csv file in normal way on any platform. That
is, open your csv file as :
Or
Example 1: writerow()
import csv
f = open("D:\\pythonprograms\\data.csv", 'w')
wr = csv.writer(f)
wr.writerow(['Name' , 'Class'])
wr.writerow(['Amit' , 'XII'])
wr.writerow(['Ankur' , 'XII'])
f.close()
Output: Data.csv
Name,Class
Page 5 of 71
Amit,XII
Ankur,XII
Example 2: writerows()
import csv
fields = ['Name' , 'Class' , 'Subject']
rows = [['Amit' , 'XII' , 'CS'] ,
['Sumit' , 'X' , 'IP'] ,
['Ashu' , 'XI' , 'CS']]
Page 6 of 71
CSV files are opened with __________argument to supress EOL translation.
Ans. newline =''
Page 7 of 71
wobj = csv.writer(f)
n = int(input("Enter the number of records:"))
# writing heading
wobj.writerow(['empid', 'empname', 'gender', 'department', 'salary'])
for i in range(n):
empid = int(input("Enter the Employee ID:"))
empname = input("Enter the Employee Name:")
gender = input("Enter the Gender:")
department = input("Enter the department:")
salary = int(input("Enter the salary:"))
data = [empid, empname, gender, department, salary]
wobj.writerow(data)
f.close()
writedata()
Output:
Enter the number of records:2
Enter the Employee ID:101
Enter the Employee Name:amit
Enter the Gender:male
Enter the department:admin
Enter the salary:10000
Enter the Employee ID:105
Enter the Employee Name:rani
Enter the Gender:female
Enter the department:hr
Enter the salary:15000
Page 8 of 71
is greater than 50000 else it should display “Salary is less, cannot
Save”
import csv
def writedata():
f = open("employee.csv", 'a', newline = '')
wobj = csv.writer(f)
empid = int(input("Enter the Employee ID:"))
empname = input("Enter the Employee Name:")
gender = input("Enter the Gender:")
department = input("Enter the department:")
salary = int(input("Enter the salary:"))
if salary > 50000:
data = [empid, empname, gender, department, salary]
wobj.writerow(data)
else:
print("Salary is less, cannot save")
f.close()
writedata()
Output 1:
Enter the Employee ID:106
Enter the Employee Name:Sumit
Enter the Gender:Male
Enter the department:Mechanical
Enter the salary:10000
Salary is less, cannot save
Output 2:
Enter the Employee ID:110
Enter the Employee Name:ramesh
Enter the Gender:male
Enter the department:it
Enter the salary:500000
Page 9 of 71
Example 6: Write a program to open "xyz.csv" file and write book no,
book name and no of pages with separator as tab.
import csv
f1 = open('xyz.csv', 'w', newline = '')
w1 = csv.writer(f1, delimiter = "\t")
w1.writerow(['BookNo', 'BookName', 'Pages'])
while True:
op = int(input("Enter 1 to add and 0to exit"))
if(op == 1):
Bookno = int(input("Enter Book No: "))
Bookname = input("Enter Book Name: ")
Pages = int(input("Enter Pages: "))
w1.writerow([Bookno, Bookname, Pages])
elif op == 0:
break
f1.close()
Page 10 of 71
readerobj = csv.reader(filehandle, delimiter=','
Where filehandle = filehandle returned from open() function
delimiter = delimiter to be used to separate columns
Page 11 of 71
['Amit', 'XII', 'CS'] ['Amit', 'XII', 'CS']
['Sumit', 'X', 'IP'] ['Sumit', 'X', 'IP']
['Ashu', 'XI', 'CS'] ['Ashu', 'XI', 'CS']
Page 12 of 71
Amit CS
Sumit IP
Ashu CS
Example 5: next() function two times then it will skip two lines from
beginning
import csv
f = open("D:\\pythonprograms\\data.csv", 'r')
row = csv.reader(f)
next(row) # next() function will jump to the next row.
next(row)
for i in row :
print(i[0] , i[2])
Output:
Sumit IP
Ashu CS
import csv
with open("student.csv", 'r') as f:
reader = csv.reader(f)
for row in reader:
Page 14 of 71
print(row)
Output:
['Rollno', 'Name', 'Marks']
[]
['101', 'ankur', '78.0']
Where have these empty
[]
rows come from?
['102', 'ashish', '75.0']
We never entered empty
[] rows.
['103', 'aman', '70.0']
Then what is the source
[] / reason of these empty
['104', 'ankita', '80.0'] rows?
[]
['105', 'Ayushi', '75.0']
[]
We never entered empty rows. Then where have these empty rows come from? Any idea?
We did not specify the newline argument in the file open ( ) function while creating / writing
this csv file (student.csv , in this case) and thus EOL translation took place , which resulted
in the blank rows after every record while reading . In fact, the above shown file data was
internally stored as:
Page 17 of 71
Example 8: Write a user defined function named display() to display
the records and also the number of records from the file.
import csv
def display():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',') #change delimiter value if some
other value specified in question
c =0
next(robj) #skip heading
for i in robj:
print(i)
c+=1
if c == 0:
print("No records")
else:
print("Number of records", c)
f.close()
display()
Output:
['101', 'ankur', '75.0']
['102', 'aman', '70.0']
['103', 'yuvika', '89.0']
['104', 'chetna', '90.0']
['105', 'usha', '99.0']
Number of records 5
Page 18 of 71
Example 9: Write a user defined function named avgmarks() to display
the Average marks of all the Students.
import csv
def avgmarks():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
c =0
s=0
next(robj) #skip heading
for i in robj:
s += float(i[2]) #float(i[-1]) can also be used
c+=1
if c == 0:
print("No records")
else:
print("Average Marks:", s/c)
f.close()
avgmarks()
Output:
Average Marks: 84.6
Page 19 of 71
import csv
def avgmarkscs():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
c =0
s=0
next(robj) #skip heading
for i in robj:
if i[3] == 'cs':
s += float(i[-2])
c+=1
if c == 0:
print("No records")
else:
print("Average marks of CS Dept students:", s/c)
f.close()
avgmarkscs()
Output:
Average marks of CS Dept students: 88.0
Page 20 of 71
import csv
def malestudent():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
c =0
next(robj) #skip heading
for i in robj:
if i[4] == 'male':
print(i)
c+=1
if c == 0:
print("No records")
else:
print("Number of male students:", c)
f.close()
malestudent()
Output:
['101', 'ankur', '75.0', 'cs', 'male']
['102', 'aman', '70.0', 'civil', 'male']
Number of male students: 2
Page 21 of 71
import csv
def count_stud():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
male =0
female=0
next(robj) #skip heading
for i in robj:
if i[4] == 'female':
female+=1
elif i[4] == 'male':
male += 1
if male == 0 and female == 0:
print("No records")
else:
print("Number of male students:", male)
print("Number of female students:", female)
f.close()
count_stud()
Output:
Number of male students: 2
Number of female students: 3
Example 13: Write a user defined function named search() and get
roll number as input and search and prints the record of the student
which matches the entered roll number.
Page 22 of 71
import csv
def search():
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
rno = int(input("Enter the Roll Number to be searched:"))
c=0
next(robj) #skip heading
for i in robj:
if int(i[0]) == rno:
print(i)
c+=1
break
if c == 0:
print("No matching records found")
f.close()
search()
Output:
Enter the Roll Number to be searched:103
['103', 'yuvika', '89.0', 'mechanical', 'female']
Page 23 of 71
f = open("student.csv", 'r')
robj = csv.reader(f, delimiter = ',')
c=0
next(robj) #skip heading
for i in robj:
if float(i[2]) > marks:
print(i)
c+=1
if c == 0:
print("No matching records found")
else:
print("Number of records:", c)
f.close()
search(85)
Output:
['103', 'yuvika', '89.0', 'mechanical', 'female']
['104', 'chetna', '90.0', 'cs', 'female']
['105', 'usha', '99.0', 'cs', 'female']
Number of records: 3
import csv
def copystud() :
f1 = open("student.csv", 'r')
Page 24 of 71
f2 = open("student1.csv", 'w',newline = '')
robj = csv.reader(f1)
wobj = csv.writer(f2)
c = 0
wobj.writerow(next(robj)) #writing heading
for i in robj:
if i[3] == 'cs':
wobj.writerow(i)
c += 1
if c == 0 :
print("No records")
else:
print("Number of records:", c)
f1.close()
f2.close()
copystud()
Output:
Page 26 of 71
max_value = float(i[2])
rec = i
c += 1
if c == 0 :
print("No records")
else:
print("Record with maximum mark is:", rec)
f.close()
maxmarks()
Output:
Record with maximum mark is: ['105', 'usha', '99.0', 'cs', 'female']
Example 19: A file data.csv has come with separator ':' but your
system can only read ';' Write a progam to convert to “new.csv”
file. Write a program to change the separator of the file.
import csv
f1 = open("data.csv", 'r')
f2 = open("new.csv", 'w', newline = '')
r1 = csv.reader(f1, delimiter = ":")
w1 = csv.writer(f2, delimiter = ";")
for row in r1 :
w1.writerow(row)
f1.close()
f2.close()
Example 20: Ronit has a CSV file “marks.csv” which has name, class
and marks separated by comma. He is writing a Python program to copy
only the name and class to another CSV file “class.csv”. He has
written the following code. As a programmer, help him to
successfully execute the given task.
import csv
file = open('class.csv', 1 , newline="")
writer = csv.writer(file)
2 open('marks.csv') as csvfile:
Page 27 of 71
data = csv. 3 (csvfile)
for row in data:
writer.writerow([ 4 , 5 ])
file.close()
1. In which mode should Ronit open the file to make a new file?
2. Which Python keyword should be used to manage the file stream?
3. Fill in the blank in Line 3 to read the data from a csv file.
4. Fill in the blank to write name into marks.csv
5. Fill in the blank to write class into marks.csv.
import csv
file = open('class.csv','w', newline="")
writer = csv.writer(file)
with open('marks.csv') as csvfile:
data = csv.reader(csvfile)
for row in data:
writer.writerow([row[0],row[1]])
file.close()
Example 21: Ronit has a CSV file “marks.csv” which has name, class
and marks separated by comma. He is writing a Python program to copy
only rows of students of class 2 to another CSV file “class.csv”. He
has written the following code. Help him to successfully execute the
given task.
import csv
file = open('class.csv', 'w' , 1 )
w1 = 2 (file)
with open('marks.csv') as 3 :
data = csv. reader(csvfile)
for row in data:
if 4 == '2' :
writer. 5 (row)
file.close()
Page 28 of 71
1. While opening the file what needs to be added to suppress
extra EOL during writing?
2. Which csv function is used to return an object to be used for
writing into a file?
3. Fill in the bank with the name of the filehandle to be used.
4. Fill in the blank to select the right field which needs to be
compared with 2.
5. Fill in the blank with correct function to write in csv file.
import csv
file = open('class.csv', 'w' ,newline="")
w1 = csv.writer(file)
with open('marks.csv') as csvfile:
data = csv. reader(csvfile)
for row in data:
if row[1]== '2' :
writer.writerow(row)
file.close()
Q. Write a program to count number of records present in “data.csv”
file.
Ans.
import csv
f = open("data.csv" , "r")
d = csv.reader(f)
next(f) #to skip header row
r = 0
for row in d:
r = r+1
print("Number of records are " , r)
Page 29 of 71
Role of csv reader object:
Create()
Search()
Page 31 of 71
_________=csv.writer(fw) #Statement2
csvwriter.writerow(["Cus_No","Name","Ph_No"])
n=int(input("Enter total number of Customer"))
for i in range(n):
cusno=int(input("Enter Customer no."))
Name=input("EnterName")
Ph_No=int(input("EnterPhone No."))
Rec=[cusno,Name,Ph_No]
csvwriter.writerow(_________) #Statement 3
fw.close()
def Display_CSV():
fr=open(_________,"r") #Statement 4
cusreader=csv.reader(fr)
i=0
for _________ in cusreader: #Statement 5
if i%2==0:
print(rec[0],'\t',rec[1],'\t',rec[2])
else:
pass
i+=1
fr.close()
Create_CSV()
Display_CSV()
Solution:
import csv
def Create_CSV():
fw=open("customer.csv","w")
csvwriter=csv.writer(fw)
csvwriter.writerow(["Cus_No","Name","Ph_No"])
n=int(input("Enter total number of Customer"))
for i in range(n):
cusno=int(input("Enter Customer no."))
Name=input("EnterName")
Page 32 of 71
Ph_No=int(input("EnterPhone No."))
Rec=[cusno,Name,Ph_No]
csvwriter.writerow(Rec)
fw.close()
def Display_CSV():
fr=open("customer.csv","r")
cusreader=csv.reader(fr)
i=0
for rec in cusreader:
if i%2==0:
print(rec[0],'\t',rec[1],'\t',rec[2])
else:
pass
i+=1
fr.close()
Create_CSV()
Display_CSV()
I. Identify suitable code for the blank space in line marked as Statement-1.
a) include
b) add
c) Import
d) import
II. Identify the missing code for the blank space in line marked as Statement-2.
a) Customer
b) reader
c) csvwriter
d) writer
III. Identify the argument name for the blank space in line marked as Statement-3?
a) Row
b) Rec
Page 33 of 71
c) row
d) rec
IV. Identify the missing file name for the blank space in line marked as Statement-4?
a) customer
b) customer.csv
c) customer.txt
d) customer.dat
V. Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec
import csv
# Function to add a new record in CSV file
def ______(Country,Capital): #Statement-1
f=open("CAPITAL.CSV","______") #Statement-2
fwriter=csv.writer(f)
fwriter.writerow([______]) # Statement-3
f.close()
Page 34 of 71
NewReader=csv.______(NF) # Statement-4
for rec in NewReader:
if len(rec)!=0:
print(rec[0],rec[1])
AddNewRec("INDIA","NEW DELHI")
AddNewRec("CHINA","BEIJING")
ShowRec() # Statement-5
Solution:
import csv
# Function to add a new record in CSV file
def AddNewRec(Country,Capital):
f=open("CAPITAL.CSV","w")
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f.close()
def ShowRec():
with open("CAPITAL.CSV","r") as NF:
NewReader=csv.reader(NF)
for rec in NewReader:
if len(rec)!=0:
print(rec[0],rec[1])
AddNewRec("INDIA","NEW DELHI")
AddNewRec("CHINA","BEIJING")
ShowRec()
Page 35 of 71
II. Choose the file mode to be passed to add new records in
Statement-2.
a) w
b) r
c) w+
d) a
IV. Choose the correct option for Statement-4 to read the data from
a csv file.
a) Reader()
b) reader()
c) read
d) reader
Page 36 of 71
f = open('user.csv', '____', newline ='') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName, PassWord])
f.close()
Solution:
import csv
def addCsvFile (UserName, PassWord): # to write / add data into the
CSV file
f = open('user.csv', 'a', newline ='')
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName, PassWord])
f.close()
Page 37 of 71
addCsvFile ("Biplab", "123@456")
addCsvFile("Arunima","aru@nima")
addCsvFile("Poonam","myname@FRD")
readCsvFile()
II. In which mode, Rinsha should open the file to add data into the
file.
a. r
b. a
c. w
d. w+
III. Fill in the blank in Line 3 to read the data from a csv file.
a. writer()
b. reader()
c. write()
d. read()
Q4. Consider the following csv file and the code fragment associated
with the following csv file:
SLNO BOOKNAME PRIC
Page 38 of 71
E
1 Pride and Prejudice 200
2 Gone with the Wind 250
3 The little prince 170
4 Anne of Green Gables 190
5 The Giving Tree 210
import csv
f = open('d:\\stud.csv')
fobj=csv.reader(f)
for k in fobj:
for j in k:
print(j, end="")
break
f.close()
II. What will be the output printed by the above code if the break
is replaced with continue?
a. SLNO12345
b. SLNO
c. The entire content
d. Error
III. What will occur if the file stud.csv is not existing in the
mentioned path?
a. It will create a new one
b. It will create an error
c. None of the above
d. It will cause a system reboot
Page 39 of 71
IV. Which statement in the above code will help to move to the next
record?
a. fobj.next()
b. next(fobj)
c. fobj.move()
d. fobj.forward()
Q5. Sai Krishna has created the following csv file named item.csv:
ITEMNO NAME PRICE
101 PENCIL 5
102 PEN 10
103 NOTE BOOK 15
He has written the following program for managing the file. Help him
to find the answers for the following questions.
import csv
f = open('d:\\item.csv','r')
fobj=csv.reader(f)
head=next(f)
print(head) #Line1
for k in fobj:
print(k) #Line2
break
else:
print(k) #Line3
n=next(f)
print(n) #Line4
f.close()
Page 40 of 71
II. What will be printed by Line2?
a. 101,PENCIL,5
b. ITEMNO, NAME, PRICE
c. 102,PEN,10
d. 103,NOTEBOOK,156
St_Id is Student ID
(integer) ST_name is
Page 41 of 71
Student Name
(string)
ANSWER:
import csv
def Accept():
lst=[]
for a in range(n):
res=input("Enter Result")
lst.append(data)
Page 42 of 71
headings=["Student ID","Student Name","Game
Name","Result"]
csvwriter=csv.writer(f)
csvwriter.writerow(headings)
for a in range(n):
csvwriter.writerow(lst[a])
f.close()
def wonCount():
f=open("Result.csv","r")
csvreader=csv.reader(f,delimiter=",")
head=list(csvreader)
for x in head:
if x[3]=="WON":
print(x)
f.close()
Accept()
wonCount()
Output:
How many records you want to enter.3
Enter Employee ID 11
Enter Employee NameAmit
Enter the Designationteacher
Enter the tax amount125
Enter Employee ID 12
Page 43 of 71
Enter Employee Namenamit
Enter the Designationsupervisor
Enter the tax amount150
Enter Employee ID 13
Enter Employee Namesuresh
Enter the Designationteacher
Enter the tax amount25
Total tax collected 300
Incomplete Code
import ____ #Statement-1
fh = open(____,____, newline='') #Statement-2
stuwriter = csv. ____ (fh) #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [____] #Statement-4
Page 44 of 71
data.append(rec)
stuwriter.____ (data) #Statement-5
fh.close()
II. Identify the missing code for blank space in line marked as
Statement-2?
(a) "School.csv","w"
(b) "Student.csv","w"
(c) "Student.csv","r"
(d) "School.csv","r"
III. Choose the function name (with argument) that should be used in the
blank space of line marked as Statement-3
(a) reader(fh) (b) reader(MyFile)
(c) writer(fh) (d) writer(MyFile)
IV. Identify the suitable code for blank space in line marked as
Statement-4.
(a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
(b) ROLL_NO, NAME, CLASS, SECTION
(c) 'roll_no','name','Class','section'
(d) roll_no,name,Class,sectionc
V. Choose the function name that should be used in the blank space of
line marked as Statement-5 to create the desired CSV File?
(a) dump() (b) load()
(c) writerows() (d) writerow()
Solution:
Page 45 of 71
import csv #Statement-1
fh = open('Student.csv','w', newline='') #Statement-2
stuwriter = csv.writer(fh) #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [roll_no,name,Class,section]#Statement-4
data.append(rec)
stuwriter.writerows(data) #Statement-5
fh.close()
Page 46 of 71
(c) .txf (d) .tfx
Page 47 of 71
(a) tuple (b) data/record
(c) field (d) format
13. While opening a file for any operation python looking for
(a) File in the system folder
(b) file in the python installation folder
(c) file in the current folder where the .py file is saved
(d) file in downloads folder
14. The default directory for the performing the most of the
functions is known as
(a) active directory
(b) current directory
(c) working directory
(d) open directory
Page 48 of 71
c) pickle d) sys
16. Manoj wants to get the name of the current directory. Select
appropriate statement for the same:
(a) os.getcd()
(b) os.getcurrentdirectory()
(c) os.getcwd()
(d) os.currentdirectory()
ANSWER KEYS
1. File 9. text editor and
spreadsheet software
(b) (a)
2. Data File 10. data/record
(a) (b)
3. Binary Files 11. A and B both are
correct
(d) (c)
4. .txt 12. All of them
(b) (d)
5. \n 13. file in the current
folder where the .py
(c) (c) file is saved
6. The file content 14.
current directory
returned to user in (b)
(a)
raw form
7. All of them 15. os
(d) (a)
8. spreadsheets or 16. os.getcwd()
database
(c) (c)
Page 50 of 71
B. csv.DictWriter(Required Attributes)
C. csv.dump(Required Attributes)
D. csv.reader(Required Attributes)
Q8. Delimiter in csv file may be changed. K
A. True
B. False
C. Both True and False
D. None
Q9. What is the delimiter in following csv file':
f=open(‘abc.csv’,delimiter=’\t’): A
A. New Line Character ‘\n’
B. Comma
C. Tab Space
D. Blank Space
Q10. CSV file uses the following file standard: K
A. UTF-8
B. RFC 4180
C. UTF-16
D. UTF-32
Q11. Which of the following statement in python is
correct after using: import csv A
A. CSV.error(Required Attributes)
B. Csv.DictWriter(Required Attributes)
C. csv.writer(Required Attributes)
D. CSV.reader(Required Attributes)
Q12. Which of the following statement in python is not
correct after using: import csv A
A. csv.sniffer(Required Attributes)
B. csv.DictReader(Required Attributes)
C. csv.load(Required Attributes)
D. csv.excel(Required Attributes)
Q13. What is the delimiter in following csv file':
f=open(‘abc.csv’,delimiter=’\n’): A
A. Tab space
Page 51 of 71
B. Comma
C. New Line Character
D. Blank Space
Q14. Which of the following statement is true: K
A. csv is not available in aplhanumeric
B. csv file is faster to handle
C. csv file is smaller in size
D. csv is used for large data transfer
Q15. In windows csv file cannot be opened with: K
A. Microsoft Excel
B. Microsoft word
C. Acrobat Reader
D. Notepad
1 2 3 4 5 6 7 8 9 10
A A B C A C C A C B
11 12 13 14 15
C C C A C
Page 53 of 71
line marked as Statement-4.
A. 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
B. ROLL_NO, NAME, CLASS, SECTION
C. 'roll_no','name','Class','section'
D. roll_no,name,Class,section
Q5. Choose the function name that should be used
in the blank space of line marked as Statement-5
to create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
Q.6 Which function is used to fetch next item from
the collection?
A. next()
B. skip()
C. omit()
D. bounce()
Q.7 Which of the following is a string used to
terminate lines produced by writer() method of
csv module?
A. Line Terminator
B. Enter key
C. form feed
D. Data Terminator
Q.8 What is the output of the following program?
import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d:
print(row)
if the file called “city.csv” contain the following
details
chennai,mylapore
Page 54 of 71
mumbai,andheri
A. chennai,mylapore
B. mumbai,andheri
C. chennai
mumbai
D. chennai,mylapore
mumbai, andheri
Q.9 What will be written inside the file test.csv
using the following program import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
with open('c:/pyprg/ch13/line2.csv', 'w') as f:
wr = csv.writer(f)
wr.writerows(D)
f.close()
A. Exam, Quarterly, Halfyearly
B. Exam Quarterly Halfyearly
C. E Q H
D. ExamQuarterly Halfyearly
Q.10 A CSV file is also known as a ….
A. Flat File
B. 3D File
C. String File
D. Random File
Q.11 Which of the following module is provided by
Python to do several operations on the CSV files?
A. py
B. xls
C. csv
D. os
Q.12 In regards to separated value files such as
.csv and .tsv, which is true?Top of Form
A. Delimiters are not used in separated value
files
B. Any character such as the comma (,) or tab
Page 55 of 71
(\t) that is used to separate the column
data.
C. Any character such as the comma (,) or tab
(\t) that is used to separate the row data
D. Anywhere the comma (,) character is used
in the file
Q.13 In separated value files such as .csv and .tsv,
what does the first row in the file typically
contain?
A. Notes about the table data
B. The author of the table data
C. The source of the data
D. The column names of the data
Q.14 Assume you have a file object my_data which
has properly opened a separated value file that
uses the tab character (‘\t’) as the delimiter. What is the proper
way to open the file using the
Python csv module and assign it to the variable
csv_reader?
Assume that csv has already been imported.
A. csv_reader = csv.reader(my_data)
B. csv_reader = csv.reader(my_data,
tab_delimited=True)
C. csv_reader = csv.tab_reader(my_data)
D. csv_reader = csv.reader(my_data,
delimiter='\t')
Q.15 When iterating over an object returned from
csv.reader(), what is returned with each iteration?
For example, given the following code block that
assumes csv_reader is an object returned from
csv.reader(), what would be printed to the console
with each iteration?
Python code:-
for item in csv_reader:
Page 56 of 71
print(item)
A. The column data as a list
B. The full line of the file as a string
C. The individual value data that is separated
by the delimiter
D. The row data as a list
1 2 3 4 5 6 7 8 9 10
C B C D C A A B D A
11 12 13 14 15
C B D D D
Page 58 of 71
newFile.close()
Fill in the Blank
A. csv.load ( )
B. csv.write( )
C. csv.reader( )
D. csvreadlines( )
Q8. The CSV files can be operated by _______ software.
A. Spreadsheet
B. Notepad
C. MS Excel
D. All of the above
Q9. which file stores data separated by comma?
A. .tsv
B. .csv
C. .py
D. .bin
Q10. Which one is not a function of csv module?
a. readline()
b. writerow()
c. reader()
d. writer()
Page 59 of 71
D. None of above
2. Which of the following parameter needs to be
added with open function to avoid blank row
followed file
A. delimiter
B. newline
C. writer,dlimiter
D. file object
3. Which is the correct way to import a csv
module?
A. import csv
B. from csv import*
C. A and B Both
D. None of above
4. Which of the following is a string used to
terminate lines produced by writer()method of
csv module?
A. Line Terminator
B. Enter Key
C. Form Feed
D. None of above
5. The writerow() function is a part of _________
module.
A. csv
B. pickle
C. writer
D. reader
6. A _____ function allows to write a single record
into each row in CSV file
A. writerows
B. writerow()
C. writer
D. None of above
7. The ____________ parameter instructs writer
Page 60 of 71
objects to only quote those fields which contain
special characters such as delimiter, quotechar or
any of the characters in lineterminator
A. csv.QUOTE_MINIMAL
B. csv.QUOTE_NONE
C. Both a&b
D. None
8. Which instances or objects return by the writer
function.
A. writerows
B. write row
C. writer
D. None of above
9. State True or False
The write row function creates header row in csv
file by default.
A. True
B. False
10. To avoid quote fields in csv.writer() function,
use _________ parameter
A. csv.QUOTE_MINIMAL
B. csv.QUOTE_NONE
C. Both a&b
D. None
11. The writer() function has how many
mandatory parameters?
A. 1
B. 2
C. 3
D. 4
12. Anshuman wants to separate the values by a $
sign. Suggest to him a pair of function and
parameter to use it
A. open,quotechar
Page 61 of 71
B. writer,quotechar
C. open,delimiter
D. writer,delimeter
13. The command used to skip a row in a CSV file
is
A. next
B. skip
C. omit
D. None of above
14. Which file mode is used only for writing data
in .csv file
A. r
B. w
C. w+
D. r+
15. State True or False
In csv file, user can insert text values and date
values with single quote like delimeter
A. True
B. False
Page 62 of 71
Case Study Questions on CSV
Q1. Rohit, a student of class 12th, is learning CSV
File Module in Python. During examination, he has
been assigned an incomplete python code (shown
below) to create a CSV File 'Student.csv' (content
shown below). Help him in completing the code
which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import ___________ #Statement-1
fh = open(______,_______ , newline='') #Statement-2
stuwriter = csv.__________________ #Statement-3
data = [ ]
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for in range (5):
roll_no =int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Page 63 of 71
Class =input("Enter Class : ")
section =input("Enter Section : ")
rec = [ ] #Statement-4
data.append(___) #Statement-5
stuwriter._________(data) #Statement-6
fh.close()
(i) Identify the suitable code for blank space in
line marked as Statement-1.
A. csv file
B. CSV
C. csv
D. Csv
(ii) Identify the missing code for blank space in
line marked as Statement-2?
A. "School.csv","w"
B. "Student.csv","w"
C. "Student.csv","r"
D. "School.csv","r"
(iii) Choose the function name (with argument)
that should be used in the blank space of line
marked as Statement-3
A. reader(fh)
B. reader(MyFile)
C. writer(fh)
D. writer(MyFile)
(iv) Identify the suitable code for blank space in
line marked as Statement-4.
A. 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
B. ROLL_NO, NAME, CLASS, SECTION
C. 'roll_no','name','Class','section'
D. roll_no,name,Class,section
(v) Identify the suitable code for blank space in
the line marked as Statement-5.
A. data
Page 64 of 71
B. record
C. rec
D. insert
(vi) Choose the function name that should be
used in the blank space of line marked as
Statement-6 to create the desired CSV File?
A. dump()
B. load()
C. writerows()
D. writerow()
Q2. Your teacher has given you a method/function
FilterWords() in python which read lines from a
text file NewsLetter.TXT, and display those words,
which are lesser than 4 characters. Your teachers
intentionally kept few blanks in between the code
and asked you to fill the blanks so that the code
will run to find desired result. Do the needful with
the following python code.
def FilterWords():
c=0
file=open('NewsLetter.TXT', '') #Statement-1
line = file. #Statement-2
word = #Statement-3
for c in ______: #Statement-4
if : #Statement-5.
print(c)
#Statement-6
FilterWords()
(i) Write mode of opening the file in statement-1?
A. a
B. ab
C. w
D. r
(ii) Fill in the blank in statement-2 to read the
Page 65 of 71
data from the file.
A. File.Read()
B. file.read()
C. read.lines( )
D. readlines( )
(iii) Fill in the blank in statement-3 to read data
word by word.
A. Line.Split()
B. Line.split()
C. line.split()
D. split.word()
(iv) Fill in the blank in statement-4, which retrieve
each word.
A. Line
B. File
C. Word
D. None of the above
(v) Fill in the blank in statement-5, which display
the word having lesser than 4 characters.
A. len(c) ==4
B. len(c)<4
C. len ( )= =3
D. len ( )==3
(vi) Fill in the blank in Statement-6 to close the
file.
A. file.close()
B. File.Close()
C. Close()
D. end()
Q3. Subrat Ray is learning to work with Binary
files in Python using a process known as
Pickling/de-pickling. His teacher has given him
the following incomplete code, which is creating a
Page 66 of 71
Binary file namely Mydata.dat and then opens,
reads and displays the content of this created file.
import ___________ #Statement-1
sqlist=list()
for k in range(5):
sqlist.append(k*k)
fout=open(“mydata.dat”, _____) #Statement-2
___________(sqlist,fout) #Statement-3
fout.close()
fin=open(“Mydata.dat”, “rb” )
mylist=____________(fin) #Statement-4
__________ # Statement-5
print(mylist) #Statement-6
(i) Which module should be imported in
Statement-1.
A. pickle
B. csv
C. file
D. text
(ii) Which file mode to be passed to write data in
file in Statement-2.
A. w+
B. w
C. wb
D. a
(iii) What should be written in Statement-3 to
write data onto the file.
A. dump()
B. write()
C. pickle.dump()
D. writeline()
(iv) Which function to be used in Statement-4 to
read the data from the file.
A. load()
Page 67 of 71
B. readline()
C. readlines()
D. pickle.load()
(v) What should be written in Statement-5 to
close the file.
A. fin.close()
B. fout.close()
C. close(fin)
D. close(fout)
(vi) The output after executing Statement-6 will
be –
A. 0 1 4 9 16
B. 1, 4, 9, 16, 25
C. [0, 1, 4, 9, 16]
D. [1, 4, 9, 16, 25]
Q.4 Snigdha is making a software on “Countries &
their Capitals” in which various records are to be
stored/retrieved in CAPITAL.CSV data file. It
consists some records(Country & Capital). She has
written the following code in python. As a
programmer, you have to help her to successfully
execute the program.
import ___________ # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a
new record in CSV file
f=open(“CAPITAL.CSV”,_________) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
____________ # Statement-3
def ShowRec(): # Fn. to display all records from CSV file
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv.___________(NF) # Statement-4
for rec in NewReader:
print(rec[0], “#”, rec[1])
Page 68 of 71
AddNewRec(“INDIA”, “NEW DELHI”)
AddNewRec(“CHINA”, “BEIJING”)
ShowRec() # Statement-5
(i) Which module should be imported in
Statement-1.
A. pickle
B. csv
C. file
D. text
(ii) Which file mode to be passed to add new
record in Statement-2.
A. w+
B. w
C. wb
D. a
(iii) What should be written in Statement-3 to
close the file.
A. close()
B. fwriter.close()
C. f.close()
D. csv.close()
(iv) Which function to be used in Statement-4 to
read the data from a csv file.
A. read()
B. readline()
C. readlines()
D. reader()
(v) The output after executing Statement-5 will be
A. (“INDIA”, “NEW DELHI”)
(“CHINA”, “BEIJING”)
B. INDIA NEW DELHI
CHINA BEIJING
C. INDIA, NEW DELHI
CHINA, BEIJING
Page 69 of 71
D. INDIA # NEW DELHI
CHINA # BEIJING
Q.5 Sangeeta has a B1.csv file which has the name,
class and section of students. She receives a B2.csv
which has similar details of students in second
branch. She is asked to add the details of B2.csv
into B1.csv. As a programmer, help her to
successfully execute the given task.
_____________ csv # Statement 1
file = open('B1.csv', _______________ , newline="")
# Statement 2
writer = csv. ________________ (file) # Statement 3
with open('B2.csv','r') as csvfile:
data = csv.reader(csvfile)
for row in data:
writer.writerow(_______________)
# Statement 4
file. ______________() # Statement 5
(i) Identify among following to complete
Statement 1.
A. import csv
B. import CSV
C. import comma separated value
D. None of these
(ii) Which mode should be used to open the file
‘B1.csv’ for Statement 2.
A. Read (r)
B. Write (w)
C. Append (a)
D. None of these
(iii) Which of the following method should be
used for Statement 3.
A. reader()
B. writer()
Page 70 of 71
C. dump()
D. load()
(iv) Which of the following is correct to complete
Statement 4.
A. data
B. file
C. csvfile
D. row
(v) Which of the following is correct to complete
Statement 5.
A. open()
B. close()
C. row
D. data
(vi) The above code is for :
A. reading
B. writing
C. both
D. None
1 C C A D C C
2 D B C C B A
3 A C C D A C
4 D B C D D --
5 A C B D B B
Page 71 of 71