0% found this document useful (0 votes)
4 views71 pages

CSV File Handling in Python

CSV (Comma Separated Values) is a text file format used to store tabular data, where each line represents a data record and fields are separated by commas. It is widely used for data transfer between programs due to its simplicity and human-readable format, although it has limitations such as lack of standard for binary data and poor support for special characters. The Python csv module provides functionality to read from and write to CSV files, allowing users to easily manipulate tabular data.

Uploaded by

anmolmaharaj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views71 pages

CSV File Handling in Python

CSV (Comma Separated Values) is a text file format used to store tabular data, where each line represents a data record and fields are separated by commas. It is widely used for data transfer between programs due to its simplicity and human-readable format, although it has limitations such as lack of standard for binary data and poor support for special characters. The Python csv module provides functionality to read from and write to CSV files, allowing users to easily manipulate tabular data.

Uploaded by

anmolmaharaj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

CSV File Handling

What is CSV? What are its Characteristics?


● CSV stands for Comma Separated Values.
● CSV is just like a text file, in a human readable format which is extensively used to
store tabular data such as a spreadsheet or database.
● Each line of the file is a data record.
● Each record consists of one or more fields, separated by comma.
● The separator character of CSV files is called a delimiter.
● Default delimiter is comma (,).
● Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.
● In CSV files space-characters adjacent to commas are ignored

See the following table

Name Class Section

Amit X A

Sumit XI B

Ashish XII C

The above table will be stored in CSV format as follows:

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

What are the Advantages of CSV files?


Ans.
• CSV is faster to handle
• CSV is smaller in size and is easy to generate
• CSV is human readable and easy to edit manually
• CSV is simple to implement and parse
• CSV is processed by almost all existing applications

What are the Disadvantages of CSV files?


Ans.
• There is no standard way to represent binary data
• There is no distinction between text and numeric values
• There is poor support of special characters and control characters
• CSV allows to move most basic data only. Complex configurations cannot be imported and
exported this way
• There are problems with importing CSV into SQL (no distinction between NULL and
quotes)

Which module is used to operate on CSV file.


Ans. To read and write in CSV files we need to import csv module.

Steps To Process a File


1. Determine the type of file usage.
a. Reading purpose: If the data is to be brought in from a file to memory
b. Writing purpose: If the data is to be sent from memory to file.
2. Open the file and assign its reference to a file object or file-handle.
Page 2 of 71
3. Process the file as required: Perform the desired operation from the file.
4. Close the file.

Python CSV Module


● CSV module provides two types of objects:
○ reader: to read from cvs files
○ writer: to write into csv files.

● To import csv module in our program, we use the following statement:


import csv

Opening / Closing a CSV File


● Open a CSV File:
f = open("demo_csv.csv","r")
OR
f = open("demo_csv.csv","w")

● Close a CSV File:


f.close()

Role of argument newline in opening of csv files:


● newline argument specifies how would python handle new line characters while working
with csv files on different Operating System.
● Additional optional argument as newline = ''(null string) with the file open() will ensure
that no translation of EOL character takes place.
As csv files are text files, while storing them, some types of translations occur - such as
translation of end of line (EOL) character as per the operating system you are working on etc.
Different operating systems store EOL characters differently.

EOL characters used in different operating systems.

Symbol / Char Meaning Operating System


CR [ \ r ] Carriage Return Macintosh

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 :

f = open("D:\\pythonprograms\\data.csv", 'w', newline ='') #(no EOL


translation)

Or

f = open("D:\\pythonprograms\\data.csv", 'r', newline ='') #(no EOL


translation)

Steps to write data to a csv file


1. Import csv module
import csv
2. Open csv file in write mode.
f = open("csv_demo.csv","w")
3. Create the writer object.
demo_writer = csv.writer(f)
4. Write data using the methods writerow() or writerows()
demo_writer.writerow(<iterable_object>)
Page 4 of 71
5. Close the file
f.close()

Writing in CSV Files


csv.writer(): writer() function returns a writer object that converts the user’s data into a
delimited string and write data into csv files using the writerow() and writerows()
functions.
Syntax:
writerobj = csv.writer(filehandle, delimiter=',')
Where filehandle = filehandle returned from open() function
delimiter = delimiter to be used to separate columns

● writerow(): Writes one row of data onto the writer object.


Syntax:
<writer_object>.writerow()
● writerows(): Writes multiple rows into the writer object
Syntax:
<writer_object>.writerows()

Significance of writer object


○ The csv.writer() returns a writer object that converts the data into a delimited string.
○ The string can be later converted into csv files using the writerow() or writerows()
method.

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']]

f = open("D:\\pythonprograms\\data.csv", 'w', newline ='')


wr = csv.writer(f)
wr.writerow(fields)
wr.writerows(rows)
f.close()
Output: Data.csv
Name,Class,Subject
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 =''

Example 3: writer() with delimiter argument


import csv
fields = ['Name' , 'Class' , 'Subject']
rows = [['Amit' , 'XII' , 'CS'] ,
['Sumit' , 'X' , 'IP'] ,
['Ashu' , 'XI' , 'CS']]

f = open("D:\\pythonprograms\\data.csv", 'w', newline ='')


wr = csv.writer(f,delimiter='|')
wr.writerow(fields)
wr.writerows(rows)
f.close()
Output:
Name|Class|Subject
Amit|XII|CS
Sumit|X|IP
Ashu|XI|CS

Example 4: Write a user defined function named writedata() to write


n number records to the file. Structure of a record is 'empid',
'empname', 'gender', 'department' and 'salary'.
import csv
def writedata():
f = open("employee.csv", 'a', 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

Example 5: Write a user defined function named writedata () to write


a record to the file. The data should be written only if the salary

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

Reading from CSV Module


To read data from csv files, reader function of csv module is used that helps in reading rows as
per the delimiter specified.
csv.reader():
Returns a reader object.
It loads data from a csv file into an iterable after parsing delimited data. Each row read from
the csv file is returned as a list of strings.
Syntax:

Page 10 of 71
readerobj = csv.reader(filehandle, delimiter=','
Where filehandle = filehandle returned from open() function
delimiter = delimiter to be used to separate columns

Steps to read data from a csv file


1. Import csv module
import csv
2. Open csv file in read mode.
f = open("csv_demo.csv","r")
3. Create the reader object.
demo_reader = csv.reader(f)
4. Fetch data through for loop, row by row.
5. Close the file
f.close()

Example 1: Returns the memory address where csv.reader object is


stored
import csv
f = open("D:\\pythonprograms\\data.csv", 'r')
row = csv.reader(f)
print(row)
Output:
<_csv.reader object at 0x000001AAEF7556C0>

Example 2: How to read entire data from data.csv file?


Code Snippet 1 Code Snippet 2
import csv import csv
f = open("D:\\pythonprograms\\data.csv", with open("D:\\pythonprograms\\data.csv", 'r')
'r') as f:
row = csv.reader(f) reader = csv.reader(f)
for i in row: for row in reader:
print(i) print(row)
Output: Output:
['Name', 'Class', 'Subject'] ['Name', 'Class', 'Subject']

Page 11 of 71
['Amit', 'XII', 'CS'] ['Amit', 'XII', 'CS']
['Sumit', 'X', 'IP'] ['Sumit', 'X', 'IP']
['Ashu', 'XI', 'CS'] ['Ashu', 'XI', 'CS']

Line-wise explanation of the code


1. The first line is importing a csv module.
2. The second line is opening a file (data.csv) in reading mode
and f is file object or file handle.
3. The third line is returning a csv.reader object that can be
used to iterate over csv file contents.
4. Then we are using loop on the object which is returned by the
previous line.

Example 3: How to read specific column from data.csv?


import csv
f = open("D:\\pythonprograms\\data.csv", 'r')
row = csv.reader(f)
for i in row :
print(i[0] , i[2]) # reading first and third column from
“data.csv” file
Output:
Name Subject
Amit CS
Sumit IP
Ashu CS

Example 4: skip the First Row (header of the table)


import csv
f = open("D:\\pythonprograms\\data.csv", 'r')
row = csv.reader(f)
next(row) # next() function will jump to the next row.
for i in row :
print(i[0] , i[2])
Output:

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

Example 6: reader() with delimiter argument


import csv
f = open("D:\\pythonprograms\\data.csv", 'r')
row = csv.reader(f, delimiter='|')
for i in row:
print(i)
Output:
['Name', 'Class', 'Subject']
['Amit', 'XII', 'CS']
['Sumit', 'X', 'IP']
['Ashu', 'XI', 'CS']

Example 7: Write a program to create a CSV file to store student


data(Rollno., Name, Marks). Obtain data from user and write 5
records into the file.
import csv
f=open("student.csv" , "w")
stuwriter=csv.writer(f)
Page 13 of 71
stuwriter.writerow(['Rollno','Name','Marks'])
for i in range (5):
print ("Student record", (i + 1))
rollno = int(input("Enter rollno :"))
name = input("Enter name :")
marks = float(input("Enter marks :"))
sturec = [rollno,name,marks]
stuwriter.writerow (sturec)
f.close()
Output:
Rollno,Name,Marks
101,ankur,78.0
102,ashish,75.0
103,aman,70.0
104,ankita,80.0
105,Ayushi,75.0

You created the file student.csv in the example 7 as shown above.


Write a program to read the records of this csv file and display them.
Note: Before we write the code for this program, recall that the given file created in the example 7
program, was created without specifying the newline argument in the file open() function.

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:

['Rollno', 'Name', 'Marks'] \ r


\ n
['101', 'ankur', '78.0'] \ r
\ n
['102', 'ashish', '75.0'] \ r
\ n
['103', 'aman', '70.0'] \ r Every data record line
was appended with EOL
\ n
character "\r\n" on
['104', 'ankita', '80.0'] \ r Windows OS because of
\ n EOL translation

['105', 'Ayushi', '75.0'] \ r


\ n
So, what is the solution?
Page 15 of 71
Create the file with newline argument set to null string ('') so
that no EOL translation could take place.
The above situation can be handled in two ways :
1. Method 1. Create/write onto csv file with newline ='' argument in
open() function.
Example: To create a csv file by suppressing the EOL
translation.
import csv
f=open("student.csv" , "w", newline='')
stuwriter=csv.writer(f)
stuwriter.writerow(['Rollno','Name','Marks'])
for i in range (5):
print ("Student record", (i + 1))
rollno = int(input("Enter rollno :"))
name = input("Enter name :")
marks = float(input("Enter marks :"))
sturec = [rollno,name,marks]
stuwriter.writerow (sturec)
f.close()
Output:
Rollno,Name,Marks
101,ankur,75.0
102,aman,70.0
103,yuvika,89.0
104,chetna,90.0
105,usha,99.0

Let us know read from the above created file.


Page 16 of 71
Output:
No blank lines in between
student.csv file contains:
the records this time
['Rollno', 'Name', 'Marks'] because the csv file was
['101', 'ankur', '75.0'] created with no EOL
translation.
['102', 'aman', '70.0']
['103', 'yuvika', '89.0']
['104', 'chetna', '90.0']
['105', 'usha', '99.0']

2. Method 2. To read from a file which is created with EOL


translation (i.e., no newline argument), open it with newline
argument set to the EOL character of the OS where the csv file
was created. For instance, if you created the csv file on a
Windows OS, open file for reading with newline argument set as
'\r\n' because the EOL on Windows is stored as '\r\n', i.e.,
as:

open (<csvfilename>, <readmode>, newline ='\r\n')


Example:
import csv
with open("student.csv", "r", newline='\r\n') as fh:
creader = csv.reader(fh)
for rec in creader: Now the file will be
read considering every
print(rec)
'\r\n' character as end
Output: of line and not as a
separate line.
['Rollno', 'Name', 'Marks']
['101', 'ankur', '75.0']
['102', 'aman', '70.0'] See, no blank lines this
['103', 'yuvika', '89.0'] time.

['104', 'chetna', '90.0']


['105', 'usha', '99.0']

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

Example 10: Write a user defined function named avgmarkscs() to


display the Average marks of the students from “cs” department.

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

Example 11: Write a user defined function named malestudent() to


display the names of all the male students.

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

Example 12: Write a user defined function named count_stud() to


display the number of male and female students from the file.
(Multi-parameter count)

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']

Example 15: Write a user defined function named search(marks) which


accepts marks as parameter and searches and prints the record of
those student whose marks is more than the value passed as parameter
“marks” in the function.
import csv
def search(marks):

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

Example 16: Write a user defined function named copystud() which


copies the records of students who belong to “CS” department to a
new file named “student1.csv”

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:

Example 17: #Write a user defined function named maxmarks() which


displays the record of the student with highest marks.
import csv
def maxmarks() :
f = open("student.csv", 'r')
robj = csv.reader(f,delimiter = ',')
c = 0
max_value = 0
next(robj) #skip heading row
for i in robj:
if c == 0:
#change delimiter value if some other value specified in question
Page 25 of 71
max_value = float(i[2]) #setting first record sal to
maximum
rec = i
if float(i[2]) > max_value:
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 18: Write a user defined function named maxmarks() which


displays the record of the student with highest marks from CS
department.
import csv
def maxmarks() :
f = open("student.csv", 'r')
robj = csv.reader(f,delimiter = ',')
c = 0
max_value = 0
next(robj) #skip heading row
for i in robj:
if i[3] == 'cs':
if c == 0:
#change delimiter value if some other value specified in question
max_value = float(i[2]) #setting first record sal
to maximum
rec = i
if float(i[2]) > max_value:

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)

Role of csv write object:

Page 29 of 71
Role of csv reader object:

Example: Creating a python program to create and search employee’s


record in csv file.
import csv
def Create():
F=open("Emp.csv",'a',newline='')
W=csv.writer(F)
opt='y'
while opt=='y':
No=int(input("Enter Employee Number:"))
Name=input("Enter Employee Name:")
Sal=float(input("Enter Employee Salary:"))
L=[No,Name,Sal]
W.writerow(L)
opt=input("Do you want to continue(y/n)?:")
F.close()
Page 30 of 71
def Search():
F=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search"))
found=0
row=csv.reader(F)
for data in row:
if data[0]==str(no):
print("\nEmployee Deatils are:-")
print ("Name : " ,data[1] )
print("Salary:",data[2])
found=1
break
if found==0:
print("The searched Employee number is not found.")
F.close()

Create()
Search()

Q1. Sudev, a student of class 12th, is learning CSV File Module in


Python. During examination, he has been assigned an incomplete
python code to create a CSV file ‘customer.csv’. Help him in
completing the code which creates the desired CSV file.
Cus_No Name Ph_No
11 Rohit 9039483993
12 Sonal 9425029546

_________ csv #Statement 1


def Create_CSV():
fw=open("customer.csv","w")

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

Q2. Viraj is making a software on “Countries and their Capitals” in


which various records are to be stored/retrieved in “CAPITAL.CSV”
data file. It consists of few records of Countries and their
Capitals. He has written the following code in python. As a
programmer, you have to help him to successfully execute the
program.

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

def ShowRec(): # Fn. to display all records from CSV file


with open("CAPITAL.CSV","r") as NF:

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

I. Choose the Name of the function in Statement-1.


a) AddNewRec
b) Addnew
c) Addrec
d) AddNewRec()

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

III. Identify the correct variables in Statement-3 to store data to


the file.
a) country,capital
b) Country,Capital
c) Coun,Cap
d) [Country,Capital]

IV. Choose the correct option for Statement-4 to read the data from
a csv file.
a) Reader()
b) reader()
c) read
d) reader

V. Choose the output which will come after executing Statement-5.


a) ‘INDIA NEW DELHI’ ‘CHINA BEIJING’
b) ‘CHINA’ ‘BEIJING’
c) INDIA NEW DELHI
d) None of the above

Q3. Rinsha of class 12 is writing a program to create a CSV file


“user.csv” which will contain user name and password for some
entries. She has written the following code. As a programmer, help
her to successfully execute the given task.
import ________ # Line 1
def addCsvFile (UserName, PassWord): # to write / add data into the
CSV file

Page 36 of 71
f = open('user.csv', '____', newline ='') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName, PassWord])
f.close()

# csv file reading code


def readCsvFile():
with open ('user.csv', 'r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0], row [1])
newFile.________ # Line 4

addCsvFile ("Biplab", "123@456")


addCsvFile("Arunima","aru@nima")
addCsvFile("Poonam","myname@FRD")
readCsvFile() # Line 5

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

# csv file reading code


def readCsvFile():
with open ('user.csv', 'r') as newFile:
newFileReader = csv.reader(newFile) #Line3
for row in newFileReader:
print (row[0], row[1])
newFile.close() # Line 4

Page 37 of 71
addCsvFile ("Biplab", "123@456")
addCsvFile("Arunima","aru@nima")
addCsvFile("Poonam","myname@FRD")
readCsvFile()

I. Name the module she should import in Line 1.


a. CSV
b. csv
c. math
d. File

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

IV. Fill in the blank in Line 4 to close the file.


a. End()
b. Close()
c. close()
d. end()

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

I. What will be the output printed by the above code?


a. SLNO12345
b. SLNO
c. The entire content
d. Error

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

I. What will be printed by Line1?


a. All the records
b. ITEMNO, NAME, PRICE
c. item.csv
d. None of the above

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

III. What will be printed by Line3?


a. 103,NOTEBOOK,15
b. Line 3 will not be executed
c. Line 3 will be executed, but nothing will be printed
d. 102,PEN,10

IV. What will be printed by Line4?


a. 101,PENCIL,5
b. ITEMNO, NAME, PRICE
c. 102,PEN,10
d. 103,NOTEBOOK,15

V. What must be written in Line 5?


a. F.close()
b. f.close()
c. fobj.close()
d. csvfile.close()

Q6. Vedansh is a Python programmer working in a school. For


the Annual Sports Event, he has created a csv file named
Result.csv, to store the results of students in different
sports events. The structure of Result.csv is : [St_Id,
St_Name, Game_Name, Result]
Where

St_Id is Student ID
(integer) ST_name is

Page 41 of 71
Student Name
(string)

Game_Name is name of game in which student is


participating(string) Result is result of the
game whose value can be either 'Won', 'Lost'
or 'Tie'

For efficiently maintaining data of the event, Vedansh


wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to
the file Result.csv. The column headings should also be
added on top of the csv file.
wonCount() – to count the number of students who have won any
event. As a Python expert, help him complete the task.

ANSWER:

import csv

def Accept():

lst=[]

n=int(input("How many records you want to enter."))

for a in range(n):

sid=int(input("Enter Student ID "))

sname=input("Enter Student Name")

game=input("Enter name of game")

res=input("Enter Result")

data=[sid, sname, game, res]

lst.append(data)

Page 42 of 71
headings=["Student ID","Student Name","Game
Name","Result"]

f=open("Result.csv", "a", newline="")

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

Q7. 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. ____ (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()

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

1. A _____ is a bunch of bytes stored on some storage devices


like hard-disk, pen-drive etc.
(a) Folder (b) File
(c) Package (d) Library

2. The _____ are the files that store data pertaining to a


specific application, for later use.
(a) Data File (b) Program File
(c) Source Code (d) Program Code

3. Which of the following format of files can be created


programmatically through python program?
(a) Data Files (b) Video Files
(c) Media Files (d) Binary Files

4. Supriya doesn't know about text file extension. Help her to


identify the same out of these:
(a) .text (b) .txt

Page 46 of 71
(c) .txf (d) .tfx

5. In python which of the following is default EOL character?


(a) \eol (b) \enter
(c) \n (d) \newline

6. Which of the following statement is correct for binary files?


(a) The file content returned to user in raw form
(b) Every line needs translation
(c) Each line is terminated by EOL
(d) It stores ASCII or Unicode characters

7. Which of the following statement is not correct for text file?


(A) Contains the information as same as its held in memory
(B) No delimiter for a line
(C) Read and write faster than binary files
(D) Common format for general work
(a) A and B only (b) A, B and C
(c) A, C and D (d) All of them

8. A basic approach to share large data among different


organizations carried out through
(a) text files
(b) binary files
(c) spreadsheets or database
(d) email attachments

9. The CSV files can be accessed by


(a) text editor and spreadsheet software
(b) only through python programs
(c) Only spreadsheet software
(d) Only through database software

10. Each line in CSV file is known as

Page 47 of 71
(a) tuple (b) data/record
(c) field (d) format

11. Read the statements and choose the correct answer:


Statement A: It is very difficult to organize unstructured data
Statement B: CSV helps into organize huge amount of data in proper
and systematic way
(a) Only Statement A is correct
(b) Only Statement B is correct
(c) A and B both are correct
(d) None of them is correct

12. Which of the following are features of CSV files:


(a) easy to read and manage
(b) smaill in size
(c) fast to process data
(d) All of them

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

15. Biswajit wants to working with files and directories through


python. Select the python module to help him to do finish his work:
a) os b) csv

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)

Q1. csv stands for: K


A. Comma Separated Value
Page 49 of 71
B. Common Shift Value
C. Chief Super Value
D. Common Separated Value
Q2. Which is correct statement to import csv module:
A. import csv A
B. import csv module
C. import csv
D. import csv module
Q3. What is the default delimiter of a csv file: K
A. New Line Character ‘\n’
B. Comma
C. Tab Space
D. Blank Space
Q4. How many line are required for one record in a csv
file: A
A. It depends on the size of the record
B. 2
C. 1
D. None of these
Q5. Is it necessary to have header line as first line in
csv file: K
A. No
B. Yes
C. Both Yes and No
D. None
Q6. Most commonly used software for opening csv file
in windows is: K
A. Acrobat Reader
B. Microsoft word
C. Microsoft Excel
D. Google Chrome
Q7. Which of the following statement in python is not
correct after using:import csv A
A. csv.DictReader(Required Attributes)

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

CSV open() and close()


(For Question 1 to 5 consider the following
content)
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.
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
Page 52 of 71
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #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
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
Q1. Identify the suitable code for blank space in
line marked as Statement-1.
A. csv file
B. CSV
C. csv
D. Csv
Q2. 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"
Q3. 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)
Q4. Identify the suitable code for blank space in

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

File Handling (CSV)


Q1. When you read csv file using csv.reader()
function it returns the values in _______ object.
A. dictionary
B. tuple
C. nested list
D. sets
Q2. CSV module allows to read contents of The
file using ____________ function.
A. csv.readrows( )
B. csv.read( )
C. csv.reader( )
D. None of the above
Q3. Observe the following code and fill the blank
in statement1 import csv with open("data.csv”)
as f:
r = csv.______(f) #statement1
for row in r:
print(row)
A. load ( )
B. read( )
C. reader( )
Page 57 of 71
D. readlines( )
Q4. 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.tab_reader(my_data)
B. csv.reader(my_data)
C. csv.reader(my_data, delimiter='\t')
D. csv.reader(my_data, tab_delimited=True)
Q5. When iterating over an object returned from
csv.reader(), what is returned with each loop ?
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?
for item in csv_reader:
print(item)
A. The full line of the file as a string
B. The row data as a list
C. The individual value separated by
delimiter
D. The column data as a list
Q6. _______ object is used to read data from csv file?
A. load ( )
B. read( )
C. reader( )
D. d. readlines( )
Q7. with open('d:\\a.csv','r') as newFile:
newFileReader = _______(newFile)
for row in newFileReader:
print (row)

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

Writing in CSV file


1. csv module allows to write multiple rows by
using which function?
A. writerows()
B. B. write row
C. 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

Q. (i) (ii) (iii) (iv) (v) (vi)

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

You might also like