[go: up one dir, main page]

0% found this document useful (0 votes)
656 views109 pages

Question Bank of Multiple-Choice Questions 2021-22 Class Xii Subject Computer Science - Chief Patron Patron

This document provides study material for the Computer Science subject for Class 12 prepared by teachers of Kendriya Vidyalaya Sangathan, Hyderabad Region. It includes multiple choice questions on Python topics covered in Class 11 and Class 12, as well as case study questions related to Python functions, lists, and modules. Teachers from various Kendriya Vidyalayas were assigned different topics to prepare questions on, including functions, lists, modules, and Python revision topics. The document aims to help students prepare for their Computer Science exam through these practice questions.

Uploaded by

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

Question Bank of Multiple-Choice Questions 2021-22 Class Xii Subject Computer Science - Chief Patron Patron

This document provides study material for the Computer Science subject for Class 12 prepared by teachers of Kendriya Vidyalaya Sangathan, Hyderabad Region. It includes multiple choice questions on Python topics covered in Class 11 and Class 12, as well as case study questions related to Python functions, lists, and modules. Teachers from various Kendriya Vidyalayas were assigned different topics to prepare questions on, including functions, lists, modules, and Python revision topics. The document aims to help students prepare for their Computer Science exam through these practice questions.

Uploaded by

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

1

केन्द्रीय विद्यालय संगठन/KENDRIYA VIDYALAYA SANGATHAN

हैदराबाद संभाग /HYDERABAD REGION

QUESTION BANK OF MULTIPLE-CHOICE QUESTIONS 2021-22

CLASS XII SUBJECT COMPUTER SCIENCE_

CHIEF PATRON
SRI K. SASEENDRAN, DEPUTY COMMISSIONER

PATRON
DR (SMT) V. GOWRI, ASSISTANT COMMISSIONER

CO ORDINATOR

SRI HONEY MEHTA, PRINCIPAL, KV GUNTUR

PREPARED & VETTED BY PGT COMPUTER SCIENCE

1. Mr PRABODH DINAKAR,KV AFS SURYALANKA


2. Mr SANDEEP UPADHAY, KV KANCHANBAUG
3. Mr RAVI KUMAR TEWARI, KV INS KALINGA
4. Mr SHASHIDHAR, KV BOLARAM
5. Mrs M CELINA SOWJANYA, KV GUNTUR
6. Mrs CH KIRAN KUMARI, KV NO1 UPPAL
7. Mr VIPIN KUMAR, KV ONGOLE
8. Mrs N SUMA, KV NO1 GOLKONDA
9. Mrs TOM JOSINA, KV TIRUMALGIRI
10. Mr ANAND GANESH, KV NO2 GOLKONDA
2

KENDRIYA VIDYALAYA SANGATHAN : HYDERABAD REGION

SUBJECT : COMPUTER SCIENCE - CLASS 12

STUDY MATERIAL PREPARATION

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

1 Mr PRABODH SURYALANKA REVISION OF PYTHON TOPICS COVERED


DINAKAR in Class XI.

MULTIPLE CHOICE QUESTIONS

1 Find the valid identifier from the following


1. 2_Myname
2. My name
3. True
4. Myname_2
Answer is:4

2 Which of the following will give output as [23,2,9,75] .If L=[6,23,3,2,0,9,8,75]


1. print(list1[1:7:2])
2. print(list1[0:7:2])
3. print(list1[1:8:2])
4. print(list1[0:8:2])
Answer is:3

3
Which of the following operator can be used with string data type?

1. ** 2. % 3. + 4. /

Answer is:3

4 Consider a tuple T = (10, 15, 25, and 30). Identify the statement that will result in an error.
1. print(T[2]) 2. T[3] = 19 3. print(min(T)) 4. print(len(T))
Answer is: 2

5
Which of the following symbol is used in Python for Multiline comments line comment?

1. /*** 2. /* 3. „‟‟ 4. #

Answer is:

6
Identify the output of the following Python statements.
3

x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]]

y = x[1][2] print(y)

1. 12.0 2. 13.0 3. 14.0 4. 15.0

Answer is: 3

7
Identify the output of the following Python statements.

L= [10, 15, 20, 25, 30]

L.insert( 3, 4)

L.insert( 2, 3)

print (lst1[-5])

1. 2 2. 3 3. 4 4. 20

Answer is:2

8
Which of the following properly expresses the precedence of operators (using parentheses) in
the following expression: 5*3 > 10 and 4+6==11

1.((5*3) > 10) and ((4+6) == 11)

2.(5*(3 > 10)) and (4 + (6 == 11))

3.((((5*3) > 10) and 4)+6) == 11

4.((5*3) > (10 and (4+6))) == 11

Answer is : 1

9
What will be the output of the following Python code?

i=1

while True:

if i%0O7 == 0:

break

print(i)
4

i += 1

1. 1 2 3 4 5 6

2. 1 2 3 4 5 6 7

3. error

4. none of the mentioned

Answer is: 1

10
values = [1, 2, 3, 4]

numbers = set(values)

def checknums(num):

if num in numbers:

return True

else:

return False

for i in filter(checknums, values):

print i

1. 1 2 3 4 2. 1 2 3. 3 4 5. 2 3 4

Answer is:1

CASE STUDY QUESTIONS (R)


1
Based on the following code answer the questions

import ___________________ #1

AR=[20,30,40,50,60,70]

FROM=random.randint(1,3)
5

TO=random.randint(2,4)

for K in range(FROM,TO+1):

print (AR[K],end=”#“)

1. What module should be imported To execute the above code #1?

(I) math (II) random (iii) pickle (iv) csv

Answer is: ii

2
What will Be the maximum value of the variables FROM and TO?

(i) 3,4 (ii) 4,3 (iii) 2,4 (iv) 4,2

Answer is : I

3
What will Be the minimum value of the variables FROM and TO?

(i) 2, 1 (ii) 1, 2 (iii) 1, 3 (iv) 1, 4

Answer is: ii

4
What possible outputs(s) are expected to be displayed on screen at the time of execution
of the program?

(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

Answer is: ii

5
What will be the output of random.random ( )

(i) 2 (II) 3.2 (iii)0.82 (iv) -0.32

Answer is : ii

6 Ramu write a list program as shown below .based on the code answer the questions

data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] #1


def fun(m):
6

print(m) #2
v = m[0][0]
print(v) #3
for row in m:
for element in row:
if v < element:
v = element
return v
print(fun(data[0])) #4

(1) The declaration of the LIST data is called


(i) Local (ii) Global (iii) local and global (iv) none of the above
Answer is : 2

7
What will be printed after execution of the line #2 ?

(i) [1,2] (ii) [[1, 2], [3, 4]] (iii) [[5, 6], [7, 8]] (iv) [5,6]

Answer is:ii

8
What will be printed after execution of the line #3 ?

(i) 4 (ii) 5 (iii)2 (iv)1

Answer is: iv

9
What will be last line of the output after execution of the line #4 ?

(i) 4 (ii) 5 (iii)2 (iv)1

Answer is: i

10
What will be the last line of the output of the above code, if line #4 is replaced with print
(fun (data (1)) ?

(i) 8 (ii) 5 (iii)2 (iv)1

Answer is: i
7

SNO NAME OF KV TOPIC ALLOTTED


THE
TEACHER

2 Mr SANDEEP KANCHANBAGH Functions: types of function (built-in functions,


UPADHAY functions defined in module, user defined functions),
creating user defined function, arguments and
parameters,
MULTIPLE CHOICE QUESTIONS

1 Which one is not the feature of Python function


(a) Modularity
(b) Reusability
(c) Simplicity
(d) difficult to find error
Ans (d)

2 What is the use of id() function in python?


(a) returns the data type of object
(b) returns the size of the the object
(c) returns the identity of object
(d) None of the above
Ans: (c)

3 Natasha is working in Python program which is function oriented. She is using the
functions already available in python. These functions are called:
(a) User defined functions
(b) In-built functions
(c) module functions
(d) reusable functions
Ans: (b)

4 Select which is false for Python function

(A) A Python function can return only a single value


(B) A function can take an unlimited number of arguments.
(C) A Python function can return multiple values
(D) Python function doesn‟t return anything unless and until you add a return statement
Ans (A)

5 Pick one the following statements to correctly complete the function body in the given
code snippet.

def f(number):
# Missing function body
print(f(5))

(a) return "number"


(b) print(number)
8

(c) print("number")
(d) return number
Ans (d)

6 Consider the following program. What is the correct flow of execution of statements:

1 def fun1(m, n):


2 c=m+n
3 print(c)
4 Return c
5 x = 10
6 y = 20
7 fun1(x,y)
8 print(“OK”)

(A) 1,2,3,4,5,6,7,8 (B) 5,6,7,1,2,3,4,8


(C) 5,6,1,2,3,4,7,8 (D) 7,8,1,2,3,4,5,6
Ans (B)

7 What is the maximum and minimum value of z in following program:

import random
x = random(2,6)
y = random(1,2)
z = x + y
print(z)

(A) min: 1 max: 2 (B) min: 2 max: 6


(C) min: 1 max: 8 (D) min: 3 max: 8
Ans (D)

8 Which is NOT the possible output of following program from given options:

import random
periph = ['Mouse', 'Keyboard', 'Printer','Monitor']
for i in range(random.randint(0,2)):
print(periph[i],'*',end=" ")

(A) Mouse *Keyboard * (B) Mouse *


(C) Mouse *Keyboard* Printer* (D) No output
Ans (C)

9 What is the output of following program:


import math
a=math.ceil(20.5)
b=a/5
c=math.floor(b)
print(c)

(A) 5 (B) 4 (C) 6 (D) None of the above


Ans (B)
9

10 What is the output of following program:


g=0
def fun1(x,y):
global g
g=x+y
return g
def fun2(m,n):
global g
g=m-n
return g
k=fun1(2,3)
fun2(k,7)
print(g)
(A) 2 (B) -2 (C) 12 (D) 5
Ans (B)

CASE STUDY QUESTIONS (R)

Lalit is a game programmer and he is designing a game where he has to use different
python functions as much as possible. Apart from other things, following functionalities are
to be implemented in the game.

(1) The players have to input their names and Lalit has to remove the unnecessary blank
spaces from the name.

(2) He is simulating a dice where random number generation is required.

(3) Since the program becomes too lengthy, Lalit wants a separate section where he can
store all the functions used in the game program.

(4) He wants to implement usage of less memory so he doesn‟t want to include all the
functions stored in separate sections.

(5) In the game, one source object generates and throws balls and the player has to catch
the balls. Here the distance and time is to be calculated so that the program can check
whether the ball was caught or missed by the player.

Lalit is feeling difficulty in implementing the above functionalities. Help him by giving
answers following questions:

11 Q.1: In functionality (1), which python module and function should be used:
(A) remove() function of string module (B) split function()
(C) trim() function of string module (D) strip() function of string module

12 Q.2: To implement functionality (2) which module can be used:


(A) random (B) randomise (C) randint (D) math

13 Q.3: In functionality (3), Lalit should use


(A) in-built functions
(B) He should write another Python program
(C) He should use a module with all the required functions
10

(D) He should make a separate section in the same Python program

14 Q.4: To implement functionality (4), which syntax is correct


(A) import <function> from <module>
(B) from <module> import <function>
(C) import all
(D) import <function>

15 Q.5: Which function is not the built-in Python function


(A) input() (B) len() (C) sqrt() (D) pow()

One student who is learning Python, is making a function-based program to find the roots
of a quadratic equation. He wrote the program but he is getting some error. Help him to
complete the task successfully:
1 from ……… import sqrt
2 Def quad(b,c,a=1):
3 x = b*b-4*a*c
4 if x<0:
5 return "Sorry, complex root(s)"
6 d = sqrt(x)
7 r1 = (-b + d)/(2*a)
8 r2 = (-b - d)/(2*a)
9 return r1,r2
10 print(quad(1,1,2))
11 root = quad(3)
12 rt = quad(2,1)

16 .1: Which python module should be used in line 1


(A) random (B) CMath
(C) math (D) Either (B) or (C)

17 Q.2: He is getting an error in line 9. What may be the error?


(A) Syntax error (B) Indentation error
(C) Logical Error (D) NameError

18 Q.3: Which statement is correct with reference to above program


(A) Two return statements are used and a function can use only one return statement
(B) Required module is not given
(C) Syntax error in line 4
(D) Error in line 11

19 Q.4: Which type of argument method is used in line 12


(A) Positional arguments (B) Default arguments
(C) Keyword arguments (D) Variable length arguments

20 Q.5: If all the errors are removed from the program then what will be the value of variable
rt after execution of line 12
(A) (-1.0, -1.0) (B) [-1.0, -1.0]
(C) "Sorry, complex root(s)" (D) -1.0, -1.0
11

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

3 Mr RAVI KUMAR INS KALINGA


TEWARI Default parameters, positional parameters, function returning
value(s),flow of execution, scope of a variable (global scope,
local scope)

MULTIPLE CHOICE QUESTIONS

1 def s_interest(prnc,time=3.rate=0.12):
return (prnc*time*rate)

s_interest(5000)
a. 800
b. 1700
c. 1800
d. 450

Ans : c. 1800

2 def func(*args):
for i in args:
print(i)

func(1, 2, 3)

a. 1
2
3
b. 1 2 3
c. Error
d. None

Ans a. 1
2
3

3 def greet(x):
if x < 0:
return "Welcome!"
else:
return "Namaste"
print(greet(1))
12

print(greet(-1))

a. Namaste
Welcome!
b. Welcome!
Namaste

c. 1!
-1
d. Error

Ans : a. Namaste
Welcome!

4 In python arguments can be passed…


a.call by value
b.call by reference
c. It gives options to user to choose
d.. Both A and B

Ans: d .Both A and B


5 If return statement is not used inside the function, the function will return:
a. NULL
b. 0
c. None
d. Arbitrary value

Ans C. None

6 Which of the following function headers is correct?


A. def fun(a = 5, b =4, c)
B. def fun(a = 5, b, c =4)
C. def fun(a, b = 5, c = 4)
D. def fun(a, b, c = 4, d)

Ans C. def fun(a, b = 2, c = 3)

7 Which of the arguments can be skipped in the function call?


a. Positional arguments
b. Default arguments
c. Keyword arguments
d. No arguments

Ans b: default arguments


13

8 Which of the following is a feature of DocString?


a) Provide a convenient way of associating documentation with Python modules,
functions, classes, and methods
b) All functions should have a docstring
c) Docstrings can be accessed by the __doc__ attribute on objects
d) All of the mentioned

Ans: d) All of the mentioned

9 def func1(f_name, val):


print(f_name(val))

func1(max, [7,8,9])
func1(min, [8,7,9])

a. 9,7
b. 7,9
c. error
d. None of the mentioned

Ans: a) 9,7

Variable defined inside a function referred to as :


10
a. Global variable
b. Default variable
c. Local variable
d. Dynamic variable

Ans: c. Local Variable

CASE STUDY QUESTIONS (R)

1 Shivam wants to know the correct name resolution rule in Python.sPlease help him.

a. Local, Enclosing, Global, Built in


b. Global, Enclosing, Local, Built in
c. Local, Global, Enclosing, Built in
d. Built in, Enclosing, Global, Local

Ans : a. Local, Enclosing, Global, Built in

2 Which type of parameter Mahesh has to use in function definition, so that any number of

arguments can be passed through function call

a. Keyword
b. Variable length.
14

c. Positional
d. Default.
Ans : b. Variable Length
3 Where does the execution of the program start?
a. user defined function
b. __main__
c. void function
d. __name__
Ans : b. __main__

4 1.def cat_dog_count(arg):
2. arg=arg.lower()
3. l=arg.split()
4. c1=l.count("cat")
5. c2=l.count("dog")
6. if c1==c2:
7. return "True"
8. else:
9. return "False"
10.b=cat_dog_count("ca dog cat do d Trip flip cat")
11.print(b)

a. 1 2 3 4 5 6 7 8 9 10 11
b. 1 10 1 2 3 4 5 10 11
c. 1 10 1 2 3 4 5 6 7 10 11
d. 1 10 1 2 3 4 5 6 8 9 10 11

Ans d. 1 10 1 2 3 4 5 6 8 9 10 11

5 Which of the following function call can be used to invoke the below function definition?
def calc(p,q,r,s)
I. calc(3,4,5,6)
II. calc (p=1,2,3,5)
III. calc(3, 4, r=3, s=5)
IV. calc(q=4, p=3,s=5,r=7)

a. All are correct


b. I, III, IV are correct
c. I, II ,III are correct
d. I & IV are correct
Ans: b I,III, IV are correct

6 Void function refers?

a. A function having the name void.


b. A function returns NULL
c. A function that returns a value.
15

d. A function returns None


Ans : d. A function returns None
7 We can pass the argument in the function call in any order using…
a. Keyword argument
b. Variable Length argument
c. No argument
d. D. default argument

Ans :a. Keyword argument

8 Rohit wants to access the global variable inside the function having the local variable same
name as Global variable. Suggest him which keyword he has to use:

a. import
b. assert
c. lambda
d. global

Ans: d. global

9 def power2(n=3):
def f(x):
return n**x
return f

print(power2()(4))

a. Error
b. 3
c. 4
d. 81

Ans d.81
10 def double(x):
return 2*x
def apply(f,data):
return f(data)
print(apply(double,[1,2,3]))
a. [1, 2, 3, 1, 2, 3]
b. [2,4,6]
c. 2*[1,2,3]
d. Error
Ans a.[1, 2, 3, 1, 2, 3]
16

NAME OF THE TEACHER KV TOPIC ALLOTTED


SNO

4 Mr SHASHIDHAR BOLARUM
Introduction to files, types of files (Text file, Binary file, CSV file

relative and absolute paths


MULTIPLE CHOICE QUESTIONS

1 How many types of files are there in python?


a) 1 b ) 2 c) 3 d) 4
Answer b) 2

2 The files that consists of human readable characters


a. Text file b) Binary file c) Both Text and Binary file d) None of the above.

Answer : a)Text File

3 Each line of a text file is terminated by a special character, called?


a. End of file b) End of byte c) End of line d) All the above

c) End of line

4 Trying to open a binary file using a text editor will show:


a. Garbage values b) ASCII values c) Binary character d) Unicodes

Answer : a) Garbage Values.

5 In file handling, what does this terms means “r, a”?


a) read, append b) append, read c) write, append d) none of the mentioned
Answer : a) read, append

6 Which function is used to read single line from file?


a) readline() b) readlines() c) readstatement() d) readfullline()
Answer: a) readline()

7 Which function is used to close a file in python?


a) close() b) stop() c) end() d) closefile()
answer : a) close()

8
A file maintains a __________ which tells the current position in the file where
writing or reading will take place.
17

a. line b. file pointer c. list d. order


Answer : b. file pointer

9
Which of the following file modes opens a file for appending and reading in a
binary file and moves the files pointer at the end of the file if the file already
exists or creates a new file?

a. .a b. .a+ c. .ab+ d. .ab


Answer: c) ab+

10
Which method of pickle module is used to write onto a binary file?
a. dump()
b. load()
c. All of the above
d. None of the above
Answer : a) dump()

CASE STUDY QUESTIONS (R)

1 Kum. Aishwarya is running her own boutique business. She wants to store data of all
orders permanently and fast processing of data through her boutique software. Suggest
her to choose the appropriate technique among the following.
a) She can use Python Dictionaries with Text files.
b) She can use Python Dictionaries with Binary file concept.
c) She can use Python Lists without the Binary files concept.
d) She can use Python Dictionaries without the Binary file concept.

Answer : b) She can use Python Dictionaries with Binary file concept.

2 A programmer has confusion in understanding the behaviour of opening a file in


"w" mode. Clear his/her confusion, by suggesting the correct option among the
given below.
The behaviour of "w" mode is
a) Opening fails if the file already exists already.
b) Opening fails if the file does not exist already.
c) Opening will be succeeded if file exists with data and keeps the data intact.
d) Opening will be succeeded, if the file exists replaces the contents, do not
exist, creates a new file.
Answer : d)

3
Master Adithya is a class 12 student like you. He is practicing text file
programming. He has a text file named names.txt. He wants to display all
18

the names contained in the text file. He has written one of the following
codes and succeeded in getting the output. Guess which among the
following option might have given the correct output.

a) names = open("names.txt", "r") c) names = open("names.txt", "r")

for line in names: for line in names:

print(names) print("line")

b) names = open("names.txt", "r") d) names = open("names.txt", "r")

for line in names: for names in line:

print(line) print(line)

Answer : b)

4
A Student's windows O/S got corrupted. He is trying to access his files through
Command Prompt, but unable to find out all his Binary data files pertaining to his
project. Help him to find out all his binary data files by suggesting the suitable
extension name among the following.

a) .txt b) .bin c).dat d) .com

Anser c) .dat

5
Given the following directory structure. Assume that the CWD is in the root folder
where animals directory resides. What is the relative path to the feline folder?
19

a) C:/animals/feline b) animals/feline c) feline/animals d) None


of the above.

Answer : b)

6
Given the following directory structure. Assume that the CWD is in the feline folder.
What is the relative path to the file bears.gif?

a) C:/animals/ursine b) animals/ursine c) ..ursine/bears.gif d)


None of the above.

Answer : c)

7
Given the following directory structure. Assume that the CWD is in the root folder
where animals directory resides. What is the absolute path to bears.gif?

a) C:/animals/ursine b) ../animals/feline c)
20

/animals/ursine/bears.gif d) None of the above.

Answer : c)

8
Given the following directory structure. Assume that the CWD is in the feline folder
what is the relative path to lions.gif?

a) C:/animals/ursine b) lions.gif c) /animals/ursine/bears.gif


d) None of the above.

Answer : b)

9
Master Adithya could able to read contents of a text file part by part. Out of the
following which option he would have been used?

a) read() b) readlines() c) readline() readfullline()

Answer c)

10
In a program, there is a need of reading whole content of a textfile in a single shot
and store it in the form of list. Suggest the best option among the following

a) read() b) readline() c) readlines() d) None of the above

Answer c)
21

SNO NAME OF THE TEACHER KV TOPIC ALLOTTED

5 Mrs M CELINA SOWJANYA KV GUNTUR


Text file: opening a text file, text file open modes (r, r+, w,
w+, a, a+),

closing a text file, opening a file using with


clause
MULTIPLE CHOICE QUESTIONS

1
What is the default mode when the file is opened using the open() method ?

a. Write
b. Read
c. Write and read
d. Read and write

Correct answer : b) read

2
The function read() is used to

a. Read the entire content of the file


b. Read the entire content of the file in the form of list
c. Read the content of the file line by line
d. Read each string of the content of the file

Correct Answer : a) Read the entire content of the file

3
Which of the following statements is true with respect to closing a file

a. It is mandatory to close a text file which is opened


b. Python automatically closes a file
c. Python automatically closes a file if the reference object of the file is allocated to
another
d. None of the above

Correct Answer : c) Python automatically closes a file if the reference object of the file is
allocated to another

4
Which of the following statements is true?

a. Python doesn't write data to the file until you close the file using the close() method
b. If the file is opened for writing and is not closed, data is not written into the target
file.
c. Python can write data to the file even if you do not close the file
22

d. None of the above

Correct Answer : b) If the file is opened for writing and is not closed, data is not written into
the target file

5
The mode “w+” is used to open the file for

a. Read and write a text file


b. Read and write a binary file
c. Write and Read a text file
d. Write and Read a binary file

Correct Answer: c) Write and Read a text file

6
:When a file is opened in “w” mode, the file pointer is placed at

a. the beginning of the file.


b. The end of the file.
c. the middle of the file.
d. the current position of the file.

Correct Answer : a) the beginning of the file.

7
:When a file is opened in “a” mode, the file pointer is placed at

a) the beginning of the file.

b)The end of the file.

c) the middle of the file.

d) the current position of the file.

Correct Answer : b)The end of the file

8
(A) : If a file is opened using the “with” statement, you get better syntax and exceptions
handling.

(B): When a file is opened using the “with” statement, it need not be closed using the
close() function.

In the above two statements, which of the following is true?

a) Both A and B are Wrong

b) A is Wrong, but B is right.

c) A is right , but B is Wrong


23

d) Both A and B are right.

Answer : d) Both A and B are right.

9
In r+ mode, if we write the file directly, it will

a) overwrite the beginning content

b) continue reading from the previous content

c) continue writing from the previous content

d) work like the append mode

Correct Answer : a) overwrite the beginning content

10
When the file content has to be modified, we can use the ____________ mode

a. r
b. w
c. a
d. r+

Correct Answer : c)a

CASE STUDY QUESTIONS (R)

1
Rajitha, during Practical Examination of Computer Science, has been assigned an
incomplete search() function to search in a text file “CAMP.txt”. The file “CAMP.txt” is
created by his Teacher and the following information is known about the file

• File contains details of camp describing events of an adventure camp in text


format

• File contains details of adventure activities like caving, trekking, paragliding, rafting
and rock climbing Rajitha has been assigned the task to complete the code and print
the number of the word trekking

def search():

f = open("CAMP.txt",____) #Statement-1

A=____________________ #Statement-2

ct=0

for x in A:
24

p=x.split()

if p==”trekking”:

ct+=1

print(ct) _______________________# Statement-3

1.In which mode Rajitha should open the file in Statement-1?

a) r b) r+ c) rb d) wb

Correct Answer: a) r

2 Name the function that can be used by Rajitha to read the content of the file in statement
-2.

a) f.read( ) b) f.readline () c) f.readlines( ) d)f.readl()

Correct answer : c) f.readlines()

3.Which statement should Rajitha use in Statement 3 to close the file.

a) file.close() b) close(file) c) f.close() d) close()

Correct Answer: c) f.close()

2 Rahul is assigned the task of storing the information of his class mates as student records
in a text file “Stu2021.txt”.He wants to create a file to write the records.
Which of the following is not a valid mode to open a file for writing the data?
(a) w (b) r+ (c) r (d) w+
Correct Answer: (c) r

3 Rohith of class 12 is asked by his Computer Science teacher to count the number of “the”
and “and” in a text file “Book.txt”. He was able to do the task to some extent, but was
confused in some areas. Help him out to complete the task
def displaytheand():
num=0 _________ #Statement 1
N=f.read()
M=N.split()
for x in M:
if x=="the" or x== "and":
print(x) num=num+1 __________ #Statement 2
print("Count of the/My in and:",num)
1. Which of the following is the correct one to be used in the place of statement 1
a) f=open("Book.txt","w")
b) f=open("Book.txt","r")
c) f=open("Book.txt","a")
d) F=open("Book.txt","r")
Correct answer : b
2. Identify the correct statement that may be used in the place of statement 2
a) f.close()
25

b) f.close(“book.txt”)
c) close()
d) None of the above
Correct answer : a

4 Ajay is studying in an Engineering College in CSE branch. His sister, a class 12 student of
Computer Science comes to him one day asking him the difference between r+ and w+
modes of a file. What is the correct answer Ajay would give to his sister?

(a) No difference between r+ and w+


(b) In r+ mode, the file is created if it does not exist and erases the content if the file
already exists; w+ raises an error if the file does not exist
(c) In w+ mode, the file is created if it does not exist and erases the content if the file
already exists; r+ raises an error if the file does not exist
(d) Depends on the operating system
Correct answer : c

5 Aparajitha joined an MNC company in Bangalore as a Python Programmer. Her task is to


handle the data available for the company in the form of text files and perform the search
operations based on specific criteria. Now she is asked to count the number of words in
the file which start with “a” or “m” (both upper and lower cases) in a text file “Passion.txt”.
She needs your help as she is stuck up with some statements. Please help her out to
complete the task
def filecreate():
f=open("Passion.txt","r") #Statement 1
f.write() f.close() # Statement 2
def count_A_M():
f=open("Passion.txt","r") # Statement 3
A,M=0,0
r=f.read()
for x in r:
if x[0]=="A" or x[0]=="a" :
A=A+1 25 elif x[0]=="M" or x[0]=="m": M=M+1
f.close()
print("A or a: ",A)
print("M or m: ",M)
1) Choose the correct option to be used as statement 1
a) f=open("Passion.txt","r")
b) f=open("Passion.txt","r+")
c) f=open("Passion.txt","w")
d) f=open("Passion.txt","a")
Correct answer : c

2) Which of the following options can be used as statement 3


a) f=open("Passion.txt","r")
b) f=open("Passion.txt","w")
c) f=open("Passion.txt","a")
d) f=open("Passion.txt","rt")
correct answer : a and d

3) Choose the correct option to be used as statement 2


a) F.close()
26

b) f.close()
c) F.close(“passion.txt”)
d) No statement is required
Correct answer : b

6 Which of the following statements is/are true?


(a) When you open a file for reading, if the file does not exist, an error occurs.
(b) When you open a file for writing, if the file does not exist, a new file is created.
(c) When you open a file for writing, if the file exists, the existing file is overwritten with the
new file. (
d) All of the above.
Correct answer : d

7
Which of the following statements is not True

a) File method close() closes the opened file.

b) Python automatically closes a file when the reference object of a file is reassigned to
another file.

c) close() method returns a value which ensures the termination of the file stream

d) Calling close( ) method more than once is allowed.

Correct answer : c

8
What is the expected output of the given code?

f = None

for i in range (5):

with open("data.txt", "w") as f:

if i > 2:

break

print(f.closed)

a) True b) False c) None d) Error

Correct Answer: a

9
Which of the following statements is true with respect to the files in Python?

a) File can be opened with a file handle using open method without any arguments

b) File can be opened with a file handle using open method with one argument to read the
file
27

c) File can be opened with a file handle using open method with one argument to write the
file

d) File can be opened with a file handle using open method with one argument to append
the file

Correct answer : b

10 To open a file only for reading which of the following statement cannot be used :
a) f = open("PYTHON.txt")
b) f = open("PYTHON.txt”, "rt")
c) f = open("PYTHON.txt", "r")
d) f = open("PYTHON.txt",”r+”)
Correct answer : d
28

SNO NAME OF THE TEACHER KV TOPIC ALLOTTED

6 Mrs CH KIRAN KUMARI KV NO1 UPPAL


Writing/appending data to a text file using write()
and writelines(),

reading from a text file using read(),


readline( ) and readlines(),

MULTIPLE CHOICE QUESTIONS

1
The ____________ method returns a list containing each line of the file as a list item .

a) read() b) readline() c) readlines() d) readone()


Answer : c) readlines() .

2
If we want to write a sequence of strings,list, tuple into the file then we use
_________ function.

a) write() b) writelines() c) writerow() d) append()


Answer : b) writelines()

3
read() and readline() functions can be used for reading no of characters from file if
size is mentioned.

a) read() and readline() b) readlines() and readline()


c) read() and readlines() d) None of the above
Answer : a) read() and readline()

4
We can use readline( ) function which can read one line at a time from the file.

a) read() b) readline() c) readlines() d) readone()


Answer : b) readline()

5
To read twelve characters from a file object fin we use ________

a) fin.read(12) b) fin.read() c) fin.readline() d) read(12)


Answer : a) fin.read(12)

6
Python automatically flushes the file buffers before closing a file with close()
function.

a) True b) False
29

Answer : a) True

7
The ________ method in Python file handling clears the internal buffer of the file. .

a) close() b) flush() c) clear() d) open()


Answer : b) flush()

8
Suppose content of 'Myfile.txt' is

Humpty Dumpty sat on a wall

Humpty Dumpty had a great fall

All the king's horses and all the king's men

Couldn't put Humpty together again

What will be the output of the following code?

myfile = open("Myfile.txt")

record = myfile.read().split()

print(len(record))

myfile.close()

a) 24 b) 25 c) 26 d) 27
Answer : c) 26

9
To create a new file or to write on an existing file after truncating / overwriting its old
content , file has to be opened in _______ access mode

a) “w+” b) “a+” c) “r+” d) “wb”

Answer : a) “w+”

10
Which of the following options can be used to read the first line of a text file Myfile.txt?

a) myfile = open('Myfile.txt'); myfile.read()

b) myfile = open('Myfile.txt','r'); myfile.read(n)

c) myfile = open('Myfile.txt'); myfile.readline()

d) myfile = open('Myfile.txt'); myfile.readlines()


30

Answer : c) myfile = open('Myfile.txt'); myfile.readline()

11
Which of the following options can be used to read the whole content of a text file
Myfile.txt?

a) myfile = open('Myfile.txt'); myfile.read()

b) myfile = open('Myfile.txt','r'); myfile.read(n)

c) myfile = open('Myfile.txt'); myfile.readline()

d) myfile = open('Myfile.txt'); myfile.readlines()

Answer :a) myfile = open('Myfile.txt'); myfile.read()

d) myfile = open('Myfile.txt'); myfile.readlines()

12
To open a file for reading any of the following statement can be used :
a) f = open("demofile.txt")
b) f = open("demofile.txt", "rt")
c) f = open("demofile.txt", "r")
d) All of the above
Answer : d) All of the above

13
Suppose content of 'Myfile.txt' is:

Twinkle twinkle little star

How I wonder what you are

Up above the world so high

Like a diamond in the sky

What will be the output of the following code?

myfile = open("Myfile.txt")

data = myfile.readlines()

print(len(data))

myfile.close()

a) 3 b) 4 c) 5 d) 6
31

Answer : b) 4

14
Suppose content of 'Myfile.txt' is

Culture is the widening of the mind and of the spirit.

What will be the output of the following code?

myfile = open("Myfile.txt")

x = myfile.read()

y = x.count('the')

print(y)

myfile.close()

a) 2 b) 3 c) 4 d) 5

Answer : b) 3

CASE STUDY QUESTIONS (R)

1
Atif has been asked by his senior to complete the following code. The code uses a
text file namely message.txt.

def count_words(filename):

Bigwords=0

F=open(filename,‟r‟)

Data=F.___________ # line 1

words = _____________ # line 2

For w in words :

__________ # line 3

___________# line 4

return bigwords, len(words)

_______ # line 5
32

print(“total number of words : “,count)

print(“No. of big words :”,big)

i. Which function is used to read all the content of the file for line1 and store in
Data variable in string format.

a) readline() b) read(file) c) read() d) readlines()

Correct Answer : c) read()

ii. Which option is correct for completing line 2

a) Data.split() b) Data.Split() c) f.split() d) None of the above

Correct Answer : a) Data.split()

iii. Which option is correct for completing line 3 and line 4 so that the count of
words having length more than 8 characters.

a) If w>8 : b) if len(w) c) if len(w) >=8: d) if len(w) >8:


bigwords+ >8: bigwords+=1
=1
bigwords+=1
bigwords+=1

Correct Answer :

b) if len(w) >8:

bigwords+=1

iv. Which option is correct for completing line 5 so that function count_words() is
called.

a) big ,count= count_words(filename)

b) big ,count= count_words(“message.txt”)

c) big _count=count_words(“message.txt”)

d) big=count_words(“message.txt”)
count=count_words(“message.txt”)

Correct Answer : b) big ,count= count_words(“message.txt”)

2
Teacher has developed a program to count how many lines start with “T” in a text
33

file “story.txt”. To choose correct option for executing program successfully.

def countlines():

file= _______ (“story.txt”) #line1

data = __________ #line2

__________# line 3

for I in data :

if _______ : # line4

c+=1

print(“Number of lines start with T “, _____) #line5

i. Which function to be used to complete line 1

a) Read() b) open() c) read() d)Open()

Correct Answer : b) open()

ii. Which function is used to read the content from the file

a) file.read() b) readline() c) file.readlines() d) file.readline()


Correct Answer : c) file.readlines()

iii. Line3- initialize the variable for count

a) c=0 b) c=c+1 c) both d) none

Correct Answer :a) c=0

iv. choose correct condition for line3

a) i=='T' b) i[0]=='T' c) "i"==T d) i[0]==T

Correct Answer : b) i[0]=='T'

v. complete the line4

a) c b) count c) I d) data
Correct Answer :a) c

3
Kum.Anisha wants to develop a program to count the number of “Me” or “My”
words present in a text file “STORY.TXT” . But she is not sure about the code .
Help her to complete it.
34

def displayMeMY():

n=0

f=open(“story.txt” , „____‟) #line 1

N = __read() #line2

M = N.________ #line 3

for x in M :

if ____________________: #line 4

n=n+1

f.________ #line 5 Closing the file.

print(“Count of Me /My words : “, ____) #line 6

i. Which access mode to be used in line 1 to open the file .

a) w b) r c) rb d) a

Correct Answer : b) r

ii. Fill the line 2 by suitable option

a) F. b) f. c) n. d) N.

Correct Answer : f.

iii. Which method to be used to complete the line 3

a) readline() b) split() c) write() d) writelines()

Correct Answer : b) split()

iv. select the correct option to complete the line 4

a) x==me or x== my c) x==”Me” or x==”My”

b) x==”me” or “my” d) x==[“Me”,”My”]

Correct Answer :c ) x==”Me” or x==”My”

v. Which function is used to complete line 5.

a) Exit() b) close() c) end() d) Close()

Correct Answer : b) close()


35

4
Rahul is trying to perform write the data to a text file. He is not sure of the
commands to be used. Hence partially he could write the program . Help him to
complete the program.

file1 = open("myfile.txt", ____)#line1

L = ["This is Delhi \n", "This is Paris \n", "This is London"]

file1._________(L) #line2

file1.close()

file1 = open("myfile.txt", _____)#line3 opening file to add new data to existing file
.

# writing newline character

file1.write("\n")

file1._________("Today")#line4

i. Which access mode to be used in line 1 to open the file for writing on to
file.

a) w b) w+ c) wr+ d) a

Correct Answer :a) w

ii. Which function to be used in line 2 for writing a list to file.

a) write() b) writelines() c) writerow() d) writeline()

Correct Answer : b) writelines()

iii. Which access mode to be used in line3 to open the file for writing new
content on existing file without any data loss.

a) w b) w+ c) wr+ d) a

Correct Answer : d) a

iv. Which function to be used in line4 for writing a list to file.

a) write() b) writelines() c) writerow() d) writeline()

Correct Answer : a) write()


36

5
Smitha wants to copy text file “Source.txt” onto “target.txt” barring the lines starting
with a “@” sign. Help her in completing the code. def filter(oldfile, newfile):

fin=open(oldfile,___)#line1

fout=open(newfile,_____)#line2

while True :

text=__________#line3

if len(text)==0:

break

if text[0]==”@” :

continue

_____.write(text)#line4

fin._____ #line5

fout._____#line6

filter(“source.txt”,”target.txt”)

i. In which access mode oldfile to be opened. Complete the line 1 by


selecting appropriate option.

a) w b) r c) rb d) a

Correct Answer : b) r

ii. In which access mode newfile to be opened. Complete the line 2 by


selecting appropriate option.

a) w b) r c) rb d) a

Correct Answer : a) w

iii. Which of the following function can be used to complete line3 for
reading line by line.

a)fin.readline() b) fin.readlines()

c)fin.read() d) fout.readline()
37

Correct Answer :a) fin.readline()

iv. Identify the object that can be used in line4

a) fin b) fout c) Fin d) Fout

Correct Answer : b) fout

v. Identify the function that can be used in line5 and 6 to close the files

a) closed() b) close() c) end() d)eol()

Correct Answer : b) close()

6
Write the output of the following code

f = open("data.txt", "r")

d =read()

d1 = read(5)

print(d)

print(d1)

#data file contains the following data

Welcome to python program

a) Welcome to python program b) Welco c) error d) None

Correct Answer : c) error

7
Your teacher has given you a method/function FilterWords() in python which reads
data from a text file NewsLetter.TXT. 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

data = file._____ #Statement-2

line = _____ #Statement-3


38

linecount= _____: #Statement-4

print(“No of lines”,linecount)

_________ #Statement-5

FilterWords()

i. Fill in the statement 1 with appropriate access mode

a) rb b) r c) w d)a

Correct Answer : b) r

ii. Fill the statement 2 with appropriate function to read 5 characters

a) read() b) read(5) c) readline(5) d) get(5)

Correct Answer : b) read(5)

iii. Fill the statement 3 to read the remaining content of the file in list form.

a) file.read() b) file.readlines() c) file.readline() d) readlines()

Correct Answer : b) file.readlines()

iv. Fill the statement 4 to count the no. of lines in the file.

a) len() b) len(line) c) Len(line) d) len.line

Correct Answer : b) len(line)

v. Fill in the blank in Statement-5 to close the file.

a) file.close() b) File.Close() c) Close() d) end()

Correct Answer : a) file.close()

8
Renu wants to write multiple lines i.e 5 lines of text content into a text file
mylife.txt.But she is not able to do it. Help her to complete the program.

F =open( ___________) #line 1

________________ #line 2
39

Line = ____________________#line 3

_____________ #line 4

_____________ #line 5

f.close()

i. Fill line 1 with correct statement.

a) (“mylife.txt”) b) (“mylife.txt”,”w”) c) (“mylife.txt”, “ wb”) d) (mylife.txt)

Correct Answer : b) (“mylife.txt”,”w”)

ii. Choose the correct option for looping to fill line2

a) For I in range(5): c) for I in range(5):

b) for I in range(1,5): d) for I in range(5)

Correct Answer : c) for I in range(5):

iii. Fill line 3 with correct option to take the input from console IO.

a) Input(“enter a line”) b) input(“enter a line”)

c) str(“Enter a line”) d) int(input((“enter a line”) )

Correct Answer : b) input(“enter a line”)

iv. Fill line 4 with correct option to copy the line to file.

a) write(Line) b) writeline(Line) c) F.write(“Line”) d)


F.write(Line)

Correct Answer : d) F.write(Line)

v. Fill line 5 with correct option to add new line character after every line.

a) write(“ ”) b) writeline(“ ”) c) F.write(“\n”) d) write(“\n”)

Correct Answer : c) F.write(“\n”)

9
Sonu wants to create one single program to read and write data using a single file
object.But she got confused and could not complete the program. Help her to
complete it . fileobject=open("report.txt", “____”) # line 1
40

print ("WRITING DATA IN THE FILE")

print() # to display a blank line

while True:

line= input("Enter a sentence ")

fileobject.___________ #line2

fileobject.write('\n')

choice=input("Do you wish to enter more data? (y/n): ")

if choice in ('n','N'):

break

print("The byte position of file object is ",fileobject.tell())

fileobject._________ # line3

print()

print("READING DATA FROM THE FILE")

str=_______________ #line4

print(str)

___________ #line 5

i. Fill the line1 with appropriate access mode to perform both write and read
operations.

a) r+ b) w c) w+ d) a

Correct Answer : c) w+

ii. Fill Line 2 to perform write operation on to the file .

a) Writeline(line) b) write(line) c) writelines(line) d)


writerow(line)

Correct Answer : b) write(line)

iii. Fill line 3 with correct function that places file object at beginning of file

a) tell() b) seek(0) c) Seek(0) d) seek()


41

Correct Answer : b) seek(0)

iv. Fill line 4 to read to all the content of the file.

a) fileobject.read() b) read() c) fileobject.readline() d)


readrow()

Correct Answer :a) fileobject.read()

v. Fill line 5 to close the file.

a) fileobject.close() b) Fileobject.Close() c) Close() d) end()

Correct Answer : a) fileobject.close()

10
Mr.Ravi, has written code which reads each character of a text file story.txt,and
also counts and displays the occurance of alphabets of A (include small cases „a‟
too).But while doing so ,he is unable to complete the code ,help him to complete
the code.

Ex : If the file content is as follows:

Updated information

As simplified by official websites.

The function EUcount() will display the output as :

A or a :4

M or m : 2

Code :

def EUcount():

________________ #1 statement to open the file

A=0

_________________ #2 statement to read the data from the file

for x in r:

_________________# 3 statement

A=A+1
42

f.close()

print(“A or a:”,A)

1.Which of the following commands is used to open the file “Story.txt”? (marked as
#1 in the Python code)

a. f= open("story.txt",'w')

b. f= open ("story.txt ",'r')

c. f= open ("story.txt ",'r+')

d. f= open ("story.txt ",'rb')

Correct answer: b. f= open("story.txt ",'r')

2.Which of the following commands is used to read the data from the file,
Story.txt? (marked as #2 in the Python code)

a. f.read( 20)

b. f.read()

c. f.write(L,F)

d. f=pickle.dump(L)

Correct Answer b. f.read()

3. Which of the following commands is used to compare alphabets of A (include


small cases „a‟ too).

a) if x==‟A‟ or x==”a”: b) if x==‟A‟ or ”a”: c) if x=‟A‟ or x=”a”: d) if x in ‟A‟ or


”a”:

Correct answer: a) if x==’A’ or x==”a”:


43

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

7 Mr VIPIN KUMAR ONGOLE seek and tell methods, manipulation of data in


a text file
MULTIPLE CHOICE QUESTIONS

1 Which function is used to change the position of the File Handle to a given specific
position.
a. .seek()
b. read()
c. tail()
d. write()

Ans . A

2 Seek() function with negative offset only works when file is opened in -------- mode.
a. read mode
b. write mode
c. binary mode
d. All of these

Ans. C

3 What is the use of seek() method in files?


a) sets the file‟s current position at the offset
b) sets the file‟s previous position at the offset
c) sets the file‟s current position within the file
d) none of the mentioned

Ans. A

4 How do you get the current position within the file?


a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos

Ans. B

5 How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned

Ans. A
44

6 What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

Ans. D

7 If we open the file in read mode then the initial value of tell() is
a. -1
b. 0
c. 1
d. End of the file

Ans. A

8 How many arguments passed to the tell()?


a. 0
b. 1
c. 2
d. variable number of arguments

Ans. A

9 Which is the correct statement with respect of seek() function?


a. 0: sets the reference point at the beginning of the file
b. 1: sets the reference point at the current file position
c. 2: sets the reference point at the end of the file
d. All of these

Ans. D

10 What is the use of seek() method in files()?

a. sets the file‟s current position at the offset


b. sets the file‟s previous position at the offset
c. sets the file‟s current position within the file
d. none of the mentioned

Ans. A
45

CASE STUDY QUESTIONS (R)

1 What are the two built-in functions to read a line of text from standard input, which
is by default the keyboard?
A. Raw_input
B. Input
C. Read
D. Scanner

Answer. A and B

2 Which of the following statements correctly explain the function of


tell() method?
A. tells the current position within the file.
B. indicates that the next read or write will occur at that many bytes from the beginning
of the file.C. move the current file position to a different location.
D. it changes the file position only if allowed to do so else returns an error.
Answer. A, and B

3 Which of the following statements correctly explain the function of


seek() method?
A. tell the current position within the file.
B. indicate that the next read or write occurs from that position in a file.
C. determine if you can move the file position or not.
D. move the current file position to a different location at a defined offset.
Answer. D

4 Which of the following command is used to open a file “c:\temp.txt”


in read-mode only?
A. infile = open(“c:\temp.txt”, “r”)
B. infile = open(“c:\\temp.txt”, “r”)
C. infile = open(file = “c:\temp.txt”, “r+”)
D. infile = open(file = “c:\\temp.txt”, “r+”)

Answer. B

5 To read the next line of the file from a file object fobj, we use:

(a) fobj.read(2)
(b) fobj.read()
(c) fobj.readline()
(d) fobj.readlines()

Answer. C
6 What happens if no arguments are passed to the seek function?
a) file position is set to the start of file
b) file position is set to the end of file
46

c) file position remains unchanged


d) error

Answer: d

7 What does the <readlines()> method returns?


A. str
B. a list of lines
C. list of single characters
D. list of integers
Answer. B

8 Which of the following command is used to open a file “c:\temp.txt” in


append-mode?
A. outfile = open(“c:/temp.txt”, “a”)
B. outfile = open(“c:\\temp.txt”, “rw”)
C. outfile = open(“c:\temp.txt”, “w+”)
D. outfile = open(“c:\\temp.txt”, “r+”)
E. outfile = open(“c:\\temp.txt”, “a”)
Answer. A and E
9 Which of the following commands can be used to read “n” number
of characters from a file using the file object <file>?
A. file.read(n)
B. n = file.read()
C. file.readline(n)
D. file.readlines()
Answer. A

10 Which of the following functions can be used to check if a file


“logo” exists?
A. os.path.isFile(logo)
B. os.path.exists(logo)C. os.path.isfile(logo)
D. os.isFile(logo)
Answer. C
47

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

8 Mrs N SUMA NO1 Binary file: basic operations on a binary file:


GOLKONDA open using file open modes (rb, rb+, wb, wb+,
ab, ab+), close a binary file
MULTIPLE CHOICE QUESTIONS

1 If a file is opened for reading, which of the following statements is not true?
a. The file must exist on the disk on the specified path
b. If the file exists at the specified path, the file is successfully opened.
c. The file even if at a different location on disk other than the specified path, will get
opened
d. Python gives error if the file does not exist at the specified path
Answer : c) The file even if at a different location on disk other than the specified
path, will get opened.

2
To read 24 characters from a file object infi, we use
a. Infi.read() b. infi.read(24)
c. Infi.readline() d. infi.readlines
Answer: b) infi.read(24)

3
The readlines() method returns__________

a. a str b. a list of integers

c. a lit of single characters d. a list of lines


Answer : d) a list of lines.

4 Which of the following is not a valid mode to open a file.


a. ab b. rw
c. wb d.w+

Answer : b) rw

5
Which of the following functions do you use to write data in the binary format?
a. Write() b. output()
c. dump() d. send()
Answer : c) dump().

6
Which of the following command is used to open a file “c:\path.txt” in read mode
only?

a. Fin=open(“c\path.txt”,”r”) b. fin=open(“c\\path.txt”,”r”)
48

c. Fin=open(file=”c:\path.txt”,”r+”) d. fin=open(file=”c\\path.txt”,”r+”)

Answer : fin=open(“c\\path.txt”,”r”)

7
Which of the following is not a correct statement for binary files?
a) Easy for carrying data into buffer
b) Much faster than other file systems
c) Characters translation is not required
d) Every line ends with new line character „\n‟
Answer : d) Every line ends with new line character „\n‟

8
Which of the following commands can be used to read the entire contents of a file
as a string using the file object <tmpfile>?
a. tmpfile.read(n)
b. tmpfile.read()
c. tmpfile.readline()
d. tmpfile.readlines()

Answer : b. tmpfile.read()

9
Which of the following command is used to open a file “c:\temp.txt” for writing in
binary format only?
a. outfile = open(“c:\temp.txt”, “w”)
b. outfile = open(“c:\\temp.txt”, “wb”)
c. outfile = open(“c:\temp.txt”, “w+”)
d. outfile = open(“c:\\temp.txt”, “wb+”)

Answer : b. outfile = open(“c:\\temp.txt”, “wb”)

10
Trying to open a binary file using a text editor will show:
a. Garbage values
b. ASCII values
c. Binary character
d. Unicodes

Answer : a. Garbage values


49

CASE STUDY QUESTIONS (R)

1 Ms. Suman is working on a binary file and wants to write data from a list to a binary
file. Consider list object as l1, binary file suman_list.dat, and file object as f.
i ) Which of the following can be the correct statement for her?
a) f = open(„suman_list‟,‟wb‟); pickle.dump(l1,f)
b) f = open(„suman_list‟,‟rb‟); l1=pickle.dump(f)
c) f = open(„suman_list‟,‟wb‟); pickle.load(l1,f)
d) f = open(„suman_list‟,‟rb‟); l1=pickle.load(f)
Correct Answer : a) f = open(„suman_list‟,‟wb‟); pickle.dump(l1,f)
ii ) Which option will be correct for reading file for suman?
a )f = open(„suman_list‟,‟rb‟)
b )f = open(„suman_list‟,‟r‟)
c )f = open(„suman_list‟,‟r+‟)
d )f = open(„suman_list‟,‟ab‟)
Correct Answer : a) f = open(„suman_list‟,‟rb‟)
iii ) In which of the file mode existing data will be intact in binary file?
a) a
b) ab
c) w
d) wb
Correct Answer : b) ab
iv ) Which one of the following is correct statement?
a) import – pickle
b) pickle import
c) import pickle
d) All of the above
Correct Answer : c ) import pickle
v) What are the binary files used for?
a. It is used to store data in the form of bytes.
b. To store data
c. To look folder good
d. None of these
Correct Answer : a) It is used to store data in the form of bytes

2
Ms. Sejal is working on the sports.dat file but she is confused about how to complete the
code to read the data from the binary file. Suggest a suitable line for her to fulfil her.
____________ # Statement 1
def sports_read ():
f1 = _______________ # Statement 2
_________________ # Statement 3
print(data)
f1. close ()
sports.read()
i ) Identify the suitable code for blank space in line marked as Statement-1.
50

a. pickle import
b. import pickle
c. import.pickle
d. None of these
Correct Answer : b) import pickle
ii ) Identify the suitable code for blank space in line marked as Statement-2.
a. open("sports.dat","wb")
b. open("sports.dat","r")
c. open("sports.dat","rb")
d. None of these
Correct Answer : c) f1 = open("sports.dat","rb")
iii ) Identify the suitable code for blank space in line marked as Statement-3.
a. data = pickle.load(f1)
b. data = pickle.dump(f1)
c. data = pickle.load(f)
d. data = pickle.dump(f)
Correct Answer: a) data = pickle.load(f1)
iv ) What is the description of `r+b` in binary mode?
a. read and write
b. write and read
c. read only
d. none of these
Correct Answer : a) read and write
v )Which of the following file modes will not delete the existing data in binary file ?
a. wb
b. w
c. a
d. ab
Correct Answer : d) ab

3
Saritha is trying to add data onto a existing binary file and is facing difficulty in
completing the code.Help her to fill the gaps in the code.

Incomplete Code:

import pickle

print("WORKING WITH BINARY FILES")

_____________________________ # Statement 1

recno=1

print ("Enter Records of Employees")

print()
51

#taking data from user and dumping in the file as list object

while True:

print("RECORD No.", recno)

eno=int(input("\tEmployee number : "))

ename=input_____________________ # Statement 2

ebasic=int(input("\tBasic Salary : "))

allow=int(input("\tAllowances : "))

totsal=ebasic+allow

print("\tTOTAL SALARY : ", totsal)

edata=[eno,ename,ebasic,allow,totsal]

pickle.dump(_____________) # Statement 3

ans=input("Do you wish to enter more records (y/n)? ")

recno=recno+1

if ans.lower()=='n':

print("Record entry OVER ")

print()

break # retrieving the size of file

print("Size of binary file (in bytes):",

bfile.tell())

______() # Statement 4

i ) To open the file for writing the data in line marked as Statement-1.
a. bfile=open("empfile.dat","ab”)
b. bfile=open("empfile.dat","a”)
c. bfile=open("empfile.dat","wb”)
d. bfile=open("empfile.dat","w”)
Correct Answer : a) bfile=open("empfile.dat","ab”)
ii ) To accept employee name from the user in line marked as Statement-2.
a. input("\tEmployee Name : ")
52

b. input(Employee Name :)
c. input("Employee Name )
d. None of these
Correct Answer : a) input("\tEmployee Name : ")
iii ) Identify the suitable code for blank space in line marked as Statement-3.
a. edata,bfile()
b. edata,bfile
c. data,bfile
d. edata,file
Correct Answer: b) edata,bfile
iv ) Identify the suitable code for blank space in line marked as Statement-4.
a. bfile.close()
b. bfile.close
c. file.close()
d. none of these
Correct Answer : a) bfile.close()
v ) Which of the following is the correct syntax to read from a file using load
function ?
A. pickle.load(<filehandle>)
B. <object> - load.pickle(<filehandle>)
C. <object> - pickle.load(<filehandle>)

D. All of the above

Correct Answer : c) <object> - pickle.load(<filehandle>)

4
A Binary file Stock.dat has a structure [pno,pname,qty,price].A user defined function
Createfile() to input data for 3 records and add to stock.dat .There are some blanks
help in filling the gaps in the code:

Incomplete Code :

Import ___________ # Statement 1

def createfile():

File=open(“d:\\Stock.dat”,‟____‟) #Statement 2

pno=input(“Enter product no:”)

pname= input(“Enter product name:”)

qty= input(“Enter product quantity:”)

price= input(“Enter product price:”)

record=[pno,pname,qty,price]
53

_______________ # Statement 3

Print(“Record inserted”)

File.close()

Createfile()

i ) Identify the suitable code for blank space in line marked as Statement-1.
a. csv
b. CSV
c. pickle
d. PICKLE
Correct Answer : c) pickle
ii ) Identify the suitable code for blank space in line marked as Statement-2.
a. wb
b. ab
c. w
d. a
Correct Answer : b) ab
iii ) select correct statement to write data into file for Statement-3.
a. pickle.dump(record,file)

b. pickle.dump(record)

c. pickle.dump(file,record)

d. pickle.load(record,file)

Correct Answer: a) pickle.dump(record,file)


iv ) Which method is used for object deserialization ?
A. Pickling
B. Unpickling
C. All of the above
D. None of the above
Correct Answer : b) Unpickling

V )What is the last action that must be performed on a file? *

a. save

b. close

c. end

d. write

Correct Answer : b) close


54

5 A binary file “STUDENT.DAT” has structure [admission_number, Name,


Percentage]. Write a function countrec() in Python that would read contents
of the file “STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of students scoring above 75%.
________ pickle # line1
def countrec():
fobj=open("_____________","rb”) # line2
num = 0
try:
while ______: # line3
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num

i ) Identify the suitable code for blank space in line-1.


a. import
b. IMPORT
c. Import
d. None of the above
Correct Answer : a) import
ii ) Identify the suitable code for blank space in line 2.
a. STUDENT.DAT
b. STUDENTS.DAT
c. SCHOOL.DAT
d. None of the above
Correct Answer : a) STUDENT.DAT
iii ) select correct keyword to fill for line-3.
a. True

b. False

c. true

d. TRUE

Correct Answer: a) True

6
Ms.Anitha is unable understand what can be the output of the following code.Help
her in getting the output.

Import pickle

L=[20,40,50]
55

f=open(“list.dat”,‟wb‟)

Pickle.dump(l,f)

Print(“Data added successfully”)

f.close()

f=open(“list.dat”,‟rb‟)

data=pickle.load(f)

f.close()

print(data)

a. Data added successfully

[20,40,50]

b. [20,30,50]

Data added successfully

c. [20,30,50]

d. No output

Correct Answer: a) Data added successfully

[20,40,50]

7 A binary file “salary.DAT” has structure [teacherid, teacher name, salary].


Complete the code in the blanks so that it would read contents of the file
“salary.DAT” and display the details of those teachers whose salary is above
20000.
import pickle
____________________________ # line1
try:
print("tr id\t tr Name\t tr Sal")
while True:
rec=___________.load(fobj) #line2
if rec[2]>_______: #line3
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
____.close() #line 4
i ) To open the file for writing the data in line marked as line-1.
a. fobj=open("salary.dat","rb")
56

b. fobj=open("salary.dat","r")
c. fobj=open("salary.dat","r+")
d. fobj=open("data.dat","rb")
Correct Answer : a) fobj=open("data.dat","rb")
ii ) The module used in line2
a. PICKLE
b. pickling
c. pickle
d. None of these
Correct Answer : c) pickle
iii ) Identify the salary to be checked in the code marked as line-3.
a. 50000
b. 20000
c. 24000
d. 10000
Correct Answer: b) 20000
iv ) Which of the following File Modes creates a new file, if the file does not exist?
(choose one/more)
a. „r‟
b. „bw‟
c. „w‟
d. „a‟

Correct Answer : c) w
v ) What is true about Binary files
a. They are not human readable
b. the file extension is .dat
c. the file stores same format as held in memory.
d. All of the above
Correct Answer : d) All of the above
8
Mr.Rohan wants to modify salary of employee having a structure[eid,ename
,salary],but unable to fill the gaps in the code. Help him to complete the code

Import pickle

f = open('d:/student.dat','rb')

reclst = []

r=___________________________ # line 1 code to ask employee id

m=int(input(“enter correct salary”))

while True:

try:
57

rec = pickle.load(f)

reclst.append(rec) #line2 statement to add items in list at the end one by


one

except EOFError:

break

f.close()

for i in range (len(reclst)):

if reclst[i]['eid']==r:

reclst[i]['salary'] = m

f = open('d:/student.dat','___') #line 3 mode to be used to copy the data

for x in reclst:

pickle.dump(x,f)

f.close()

i ) Identify the code in line1.


a. int(input(“Enter employee id”))
b. int(“Enter employee id”)
c. int(INPUT(“Enter employee id”))
d. None of the above
Correct Answer : a) int(input(“Enter employee id”))
ii ) The module used in line2
a. PICKLE
b. pickling
c. pickle
d. None of these
Correct Answer : c) pickle
iii ) Fill in the code marked as line-3.
a. w
b. wb
c. r
d. rb
Correct Answer: b) wb

9
A binary file sports.dat contains information in the following structure:( Event,
Participant )
A code is shown below which is incomplete that would read contents from the
58

sports.dat and creates a file named Athletic.dat copying only those records from
sports.dat where the event name is “Athletics”.

import pickle

ath ( f1 , f2 ) :

l = pickle.load ( f1)

for t in l :

if ( t [ 0 ] == “________________” ) : #line 1

pickle.__________ ( t , f2 ) #line 2

f1 = open ( “ sports.dat “ , “ rb ” )

f2 = open ( “ athletics.dat “ , “ wb “ )

f.close()

f1.close()

i ) Identify the code in line1.


a. Athletics
b. Sports
c. Games
d. None of the above
Correct Answer : a) Athletics
ii ) The function to copy the data into other binary file2
a. DUMP
b. close
c. dump
d. None of these
Correct Answer : c) dump
iii ) Information stored on a storage device with a specific name is called as __________.
a. array
b. dictionary
c. file
d. tuple
Correct Answer: c) file
iv) Which of the follwong is not a valid mode to open a file?
a . ab
b. rw
c . r+
d.w+
Correct Answer: b) rw
59

10
A function searchprod( pc) in python is created to display the record of a particular
product from a file product.dat whose code is passed as an argument. Structure of
product contains the following elements [product code , product price].There is
some problem in completing the code,help to finish the code:

f = ________('d:/product.dat','rb') #line1

flag = False

pc=input(“Enter product code to be searched”)

while True:

try:

rec = pickle.load(f)

if rec['pcode'] ==_____: #line2

print('Product code:',rec['pcode'])

print('Price:',rec['price'])

flag = True

except EOFError:

break

if flag == False:

print('No Records found')

f.close()

i ) Identify the method in line1.


a. close
b. open
c. OPEN
d. None of the above
Correct Answer : b) open
ii ) The variable used to accept product code entered by the user for the line2
a. pcode
b. pc
c. code
d. None of these
Correct Answer : b) pc
60

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

9 Ms TOM JOSINA TIRUMALAGIRI import pickle module, dump() and


load() method, read, write/create,
search, append and update
operations in a binary file
MULTIPLE CHOICE QUESTIONS

1
_____________ is the process of converting Python object hierarchy into a byte
stream so that it can be written into a file.

a) Pickling

b) Unpickling

c) Dumping

d) Loading

Answer: a

2
_______ is the process of reading from a binary file

a) Pickling

b) Unpickling

c) Dumping

d) Loading

Answer: b

3
___________ of pickle module will unpickle the data coming from the binary file.

a) load()
b) dump()
c) writer()
d) insert()

Answer : a
61

4
___________ of pickle module will pickle the data in the binary file.

a) load()
b) dump()
c) writer()
d) insert()

Answer : b

5
_______________ will return the current position of file pointer in the file

a) seek()

b) search()

c) tell()

d) print()

Answer : c

6
________ places the file pointer at the specified position in the open file.

a) seek()

b) search()

c) tell()

d) print()

Answer : a

7
F.seek(20,0) will move the file pointer 20 bytes in forward direction from beginning of file.
State True or False

a) True

b) False

Answer : a

8
F1.seek(-5,1) will move the file pointer 5 bytes backwards from end of file.

State True or False


62

a) True

b) False

Answer : b

9
Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is
the file object. What is the default value of reference_point?

a) 0

b) 1

c) 2

d) 3

Answer : a

10
Which of the following statements is true?

a) pickling creates an object from a sequence of bytes

b) pickling is used for object serialization

c) pickling is used for object deserialization

d) pickling is used to manage all types of files in Python

Answer : b

CASE STUDY QUESTIONS (R)


63

1
Archit wants to create and display a Binary file named “Myfile.DAT”. Complete the
missing code to open, create and display the file.

import __________ #Line1

double=[]

for i in range(1,11):

double.append(2*i)

fo=__________________ #Line2

pickle.________________ #Line 3

fo.close()

fin=___________________ #Line4

result=________________ #Line 5

fin.close()

print(" The content of file :", result)

1. Name the module he should import in Line 1.

a) csv
b) pickle
c) binary
d) bin
Answer : b

2. Fill in the blank in Line 2 to open the file for writing the contents of the file.

a) open("Myfile.dat","w")
b) open("Myfile.dat","r")
c) open("Myfile.dat","wb")
d) open("Myfile.dat","rb")

Answer : c

3. Fill in the blank in Line 3 with the function to write entire contents to file.

a) load(double,fo)
b) dump(double,fo)
c) writer(double)
d) insert(double,fo)
Answer : b
64

4. Fill in the blank in Line 4 to open the file for displaying contents of file.

a) open("Myfile.dat","w")
b) open("Myfile.dat","r")
c) open("Myfile.dat","wb")
d) open("Myfile.dat","rb")
Answer : d

5. Fill in the blank in Line 5 read the contents of the file.

a) pickle.read(fin)
b) pickle.readline(fin)
c) pickle.readlines(fin)
d) pickle.load(fin)

Answer: d
65

2
Rohith has been given the following incomplete code for entering his
details(Name,contact number and address) to a file “Personal.DAT” and display
the contents. Complete the missing code to open, create and display the file.

import __________ #Line1

mydata=[]

name=input(“Enter Name:”)

contactno=int(input(“Enter contact number:”))

address=input(“Enter address:”)

mydata=[name,contactno,address]

f1=__________________ #Line2

pickle.________________ #Line 3

f1.close()

f2=___________________ #Line4

result=________________ #Line 5

f2.close()

print(" The content of file :", result)

1. Name the module he should import in Line 1.

a) csv
b) pickle
c) binary
d) bin
Answer : b

2. Fill in the blank in Line 2 to open the file for writing the contents of the file.

a) open("Personal.dat","w")
b) open("Personal.dat","r")
c) open("Personal.dat","wb")
d) open("Personal.dat","rb")

Answer : c

3. Fill in the blank in Line 3 with the function to write entire contents to file.
66

a) load(mydata,f1)
b) dump(mydata,f1)
c) writer(mydata)
d) insert(mydata,f1)
Answer : b

4. Fill in the blank in Line 4 to open the file for displaying contents of file.

a) open("Personal.dat","w")
b) open("Personal.dat","r")
c) open("Personal.dat","wb")
d) open("Personal.dat","rb")
Answer : d

5. Fill in the blank in Line 5 read the contents of the file.

a) pickle.read(f2)
b) pickle.readline(f2)
c) pickle.readlines(f2)
d) pickle.load(f2)

Answer: d
67

3
You are provided with some incomplete code for entering student‟s details (Rollno,
Name and marks) to a file “Student.DAT” and display the contents. Complete the
missing code to open, create and display the file.

import __________ #Line1

data=[]

rollno=int(input(“Enter Roll number:”))

name=input(“Enter Name:”)

marks=int(input(“Enter mark:”))

data=[rollno,name,marks]

fout= open("Student.dat","wb")

pickle.________________ #Line 2

fout.close()

fin=___________________ #Line3

output=________________ #Line 4

fin.close()

if ____________>=33: #Line5

print(output[1]," passed”)

else:

print(output[1]," failed”)

1. Name the module to import in Line 1.

a) csv
b) pickle
c) binary
d) bin
Answer : b

2. Fill in the blank in Line 2 with the function to write entire contents to file.

a) load(data,fout)
68

b) dump(data,fout)
c) writer(data)
d) insert(data,fout)
Answer : b

3. Fill in the blank in Line 3 to open the file for displaying contents of file.

a) open("Student.dat","w")
b) open("Student.dat","r")
c) open("Student.dat","wb")
d) open("Student.dat","rb")
Answer : d

4. Fill in the blank in Line 4 read the contents of the file.

a) pickle.read(fin)
b) pickle.readline(fin)
c) pickle.readlines(fin)
d) pickle.load(fin)

Answer: d

5 . Fill in the blank in Line 5 to display he status of students(passed/failed) based on


their mark.

a) Output[0]
b) Output[1]
c) Output[2]
d) output

Answer : c
69

4 Ritesh wants to perform the following binary file operations, as a part of his
assignment, with the help of two user defined functions/modules:

a. AddEmp() to create a binary file called Employee.DAT containing


employee information – employee number, name and salary.

b. ViewEmp() to display the name and salary of employees who are


getting Rs.50000 above as salary. The function should also display the
average salary.
Help him in filling incomplete code.

import pickle

def AddEmp():

#Line1 to open the binary file to write data


while True:
Empno = int(input("Employee number: :"))
Name = input("Name : ")
Salary = int(input("Enter Salary :"))
L = [Empno, Name, Salary]
#Line2 to write the list L into the
file
Choice = input("enter more (y/n): ")
if Choice in "nN":

break

F.close()

def ViewEmp():
Total=0
Countrec=0
C50K=0
F=open("Employee.DAT","rb")
while True:

try:

#Line3 to read from the file


Countrec+=1
Total+=R[2]
if _______ > 50000: #Line4

print(R[1],"has salary ",R[2])

C50K+=1
70

except:

break

if C50K==0:

print("No employee with salary more than


50000")

average=______________ #Line5 to find average


salary

print("average Salary = ",average)

AddEmp()

ViewEmp()

1. Write statement #Line1, to open the file “Employee.DAT” for writing only in
binary format?

a) F= open("Employee.DAT",'wb')

b) F= open("Employee.DAT",'w')

c) F= open("Employee.DAT",'wb+')

d) F= open("Employee.DAT",'w+')

Answer : a

2. Write statement, #Line2, to write the list L into the binary file,
Employee.DAT?

a) pickle.write(L,f)

b) pickle.write(f, L)

c) pickle.dump(L,F)

d) f=pickle.dump(L)

Answer : c
3. Write statement, #Line3, to read each record from the binary file
Employee.DAT?

a) R = pickle.load(F)
71

b) pickle.read(r,f)

c) r= pickle.read(f)

d) pickle.load(r,f)

Answer : a

4. Write statement , #Line4, to find employees who are getting salary more than
Rs.50000.
a) R[0]
b) R[1]
c) R[2]
d) R[3]

Answer : c
5. Write statement , #Line5, to find average salary of employees

a) Total/countrec

b) Total/C50K

c) Total/Countrec

d) average(Total)

Answer : c
72

5 Anand, a software developer, is asked to help a librarian to find some details of


books in his library. The book information is stored in a binary file Books.DAT.
Create two user defined functions/modules:

a. AddBook() to create a binary file called Books.DAT containing Book


information – Book name, Author and Price.

b. ViewBook() to display the name, Author and price of books which are
more than Rs.350 in price. The function should also display the
average price of books.
Try to fill the incomplete code to get required information for librarian.

import pickle

def AddBook():

#Line1 to open the binary file to write data


while True:
Name = input("Book Name : ")
Author= input("Author Name :
")
Price = int(input("Enter Book Price
:"))
Lst= [Name, Author, Price]
#Line2 to write the list Lst into the
file
Choice = input("enter more (y/n): ")
if Choice in "nN":

break

Fp.close()

def ViewBook():

Total=0
Count=0
C=0
F=open(________________) #Line3 to open file for
reading
while True:

try:

#Line4 to read from the file


Count+=1
Total+=Row[2]
if _______ > 350: #Line5
73

print(“Price of “,Row[1],"=
",Row[2])

C+=1

except:

break

if C==0:

print("All books are having price less than


350")

avgprice=Total/Count

print("Average Price = ",avgprice)


F.close()

AddBook()

ViewBook()

1. Fill in the blank in Line1, to open the file “Books.DAT” for writing in binary
format?

a) Fp= open("Books.DAT",'w')
b) Fp= open("Books.DAT",'wb')
c) Fp= open("Books.DAT",'wb+')
d) Fp= open("Books.DAT",'w+')

Answer : b

2. Fill in the blank in Line2, to write the list Lst into the binary file, Books.DAT?
a) pickle.write(Lst,fp)
b) pickle.write(fp, Lst)
c) pickle.dump(Lst,Fp)
d) fp=pickle.dump(Lst)
Answer : c
3. Fill in the blank in Line3, to open the file “Books.DAT” for reading
a) F= open("Books.DAT",'r')
b) F= open("Books.DAT",'r+')
c) F= open("Books.DAT",'wb+')
d) F= open("Books.DAT",'rb')
Answer : d

4. Fill in the blank in Line4, to read data from file.


a) Row=pickle.load(Fp)
b) Row=pickle.read(Fp)
74

c) Row=pickle.read(F)
d) Row=pickle.load(F)

Answer : d
5. Fill in the blank in Line5 with suitable expression:
a) Row[0]
b) Row[1]
c) Row[2]
d) Row[3]

Answer : c
75

6 John, a student of class 12 student wants to complete a search() function to


search in a pickled file Competition.dat.

· File contains details of prizes in a competition [Rollno,name, prize] format.

· File contains details of 10 participants‟ details

Arun has to complete the code and print details of prize 1.

def search():

f = open("Competition.dat", _______) # Line


-1
______________: # Line -2
while True:

rec = pickle.____________# Line -3

if(_____________): #Line -4
print(rec)
except:

pass

_________________ # Line -5

1. Fill in the blank in Line1, to open the file “Competition.DAT” for reading in
binary format?
a) w
b) r
c) wb
d) rb

Answer : d

2. Fill in the blank in Line2, to handle exceptions in statements


a) except
b) try
c) handle
d) statement
Answer : b
3. Fill in the blank in Line3, to read the records.

a) read(f)

b) readline(f)

c) load(f)
76

d) load()

Answer : c

4. Fill in the blank in Line4, to read record from file.


a) rec[0]==1
b) rec[2]==1
c) rec[prize]==1
d) rec[“prize”]==1

Answer : b
5. Fill in the blank in Line5 to close the file pointer:
a) f.end()
b) f.close()
c) f=close()
d) close(f)

Answer : b
77

7 A binary file “Book.DAT” has structure [Bookno, Book_Name, Author, Price].


Ravi, a student of class 12 Computer Science is told to create the file and search
for the number of books of a specific author by completing the blank lines.

import pickle
def createFile():
fobj=_______________ #Line1 to open file for entering data to file
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input(“Author: “)
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
_________________ #Line2 to store data to file
fobj.close()
def CountRec(Author):
fobj=_______________ #Line3 to open file for searching
num= 0
try:
while True:
rec=_____________ # Line4 to read a record
if Author==______: #Line5 to check for specific author
num = num + 1
except:
fobj.close()
return num

1. Fill in the blank in Line1, to open the file “Books.DAT” for writing in binary
format?
a) open("Book.dat","ab")
b) open("Books.DAT",'wb')
c) open("Books.DAT",'a')
d) open("Books.DAT",'w+')

Answer : a
2. Fill in the blank in Line2, to write the list rec into the binary file, Books.DAT?
a) pickle.write(rec)
b) pickle.dump(rec,fobj)
c) pickle.dump(fobj,rec)
d) fobj=pickle.dump(rec)
Answer : b
3. Fill in the blank in Line3, to open the file “Books.DAT” for searching.
a) open("Book.dat","r")
b) open("Book.dat","rb")
c) open("Book.dat","wb")
d) open("Book.dat","ab”)
Answer : b

4. Fill in the blank in Line4, to read record from file.


78

a) pickle.read(f)
b) pickle.load(f)
c) pickle.load(fobj)
d) pickle.read(fobj)
Answer : c
5. Fill in the blank in Line5 with suitable expression:
a) rec[0]
b) rec[1]
c) rec[2]
d) rec[3]
Answer : c
8 Neha, a software developer is asked to complete a search() function to search in
a pickled file Book.DAT.

· File contains details of Books [Bookno,Bname, Price] format.

· File contains details of 10 Books‟ details

Neha wants to complete the code and print details of Book with Book number
123.

def search():

fp= open("Book.dat", _______) # Line -1

______________: # Line -2

while True:

R = pickle.____________# Line -3

if(_____________): #Line -4
print(R)

except:

pass
_________________ # Line -5

1. Fill in the blank in Line1, to open the file “Book.DAT” for reading in binary
format?

a) w

b) r

c) wb
79

d) rb

Answer : d
2. Fill in the blank in Line2, to handle exceptions in statements

a) except

b) try

c) handle

d) statement

Answer : b
3. Fill in the blank in Line3, to read the records.

a) read(fp)

b) readline(fp)

c) load(fp)

d) load()

Answer : c

4. Fill in the blank in Line4, to read record from file.


a) R[0]==123
b) R[2]==123
c) R[Bookno]==123
d) R[“Bookno”]==123

Answer : b
5. Fill in the blank in Line5 to close the file pointer:

a) fp.end()

b) fp.close()

c) fp=close()

d) close(fp)

Answer : b

9 I. Neha, a class 12 student is asked to write a binary file, “Admission.DAT”, for


entering new admission student details and review the details when required. She
faced some problems in statements and see if you can fill the missing code.
import pickle
80

def newadmission():
admnlst=[]
fobj=open(“Admission.dat”,”___”) #Line1 to open file for entering data to
file
while True:
AdmnNo=int(input("Admission Number : "))
Stud_name=input("Name :")
Fathername = input(“Father’s name: “)
Phone = int(input("Phone No : "))
rec=[AdmnNo,Stud_Name,Fathername,Phone]
admnlst.append(______) #Line2 to add a record
choice=input(“Enter more y/n”)
if choice in “Nn”:
break
_________________ #Line3 to store data to file
fobj.close()

def getRecords(AdmNo):
fobj=_______________ #Line4 to open file for searching
result=pickle.load(fobj)
for rec in result:
if rec[0]==______: #Line5 to check for given admission
number
print(rec)
fobj.close()

1. Identify missing code in Line1 so that file can add more information

a) w
b) r
c) wb
d) rb

Answer : c

2. Identify missing object in Line2


a) fobj
b) R
c) rec
d) admission
Answer : c
3. Fill in the necessary function in Line3, to input data to binary file.

a) pickle.dump(“admnlst”,”fobj”)

b) pickle.dump(admnlst,fobj)

c) pickle.dump(“fobj”,“admnlst”)
81

d) pickle.dump(fobj,admnlst)

Answer : b

4. Fill in the blank in Line4, to read data from file.


a) open(“Admission.dat”,”read”)
b) open(“Admission.dat”,”r”)
c) open(“Admission.dat”,”rd”)
d) open(“Admission.dat”,”rb”)

Answer : d
5. Fill in the blank in Line5 to check for given admission number:
a) AdmnNo
b) “AdmnNo”
c) AdmNo
d) “AdmNo”

Answer : c

10 I. Ananya, a class 12 student is asked to write a binary file, “Fees.DAT”, for entering
fee details of students and review the details when required. She faced some
problems in statements and see if you can fill the missing code.
import pickle
def feeEntry():
Feelst=[]
fobj=open(“Fees.dat”,”___”) #Line1 to open file for entering data to file
while True:
AdmnNo=int(input("Admission Number : "))
Stud_name=input("Name :")
Class = input(“Enter Class: “)
Fee = int(input("Enter Fee : "))
rec=[AdmnNo,Stud_Name,Class,Fee]
Feelst.append(______) #Line2 to add a record
choice=input(“Enter more y/n”)
if choice in “Nn”:
break
_________________ #Line3 to store data to file
fobj.close()

def getRecords(AdmNo):
fobj=_______________ #Line4 to open file for searching
result=pickle.load(fobj)
for rec in result:
if rec[0]==______: #Line5 to check for given admission
number
print(rec)
fobj.close()
82

1. Identify missing code in Line1 so that file can add more information

a) w
b) r
c) wb
d) rb

Answer : c

2. Identify missing object in Line2


a) fobj
b) R
c) rec
d) admission
Answer : c
3. Fill in the necessary function in Line3, to input data to binary file.
a) pickle.dump(“Feelst”,”fobj”)
b) pickle.dump(Feelst,fobj)
c) pickle.dump(“fobj”,“Feelst”)
d) pickle.dump(fobj,Feelst)
Answer : b

4. Fill in the blank in Line4, to read data from file.


a) open(“Fees.dat”,”read”)
b) open(“Fees.dat”,”r”)
c) open(“Fees.dat”,”rd”)
d) open(“Fees.dat”,”rb”)

Answer : d
5. Fill in the blank in Line5 to check for given admission number:
a) AdmnNo
b) “AdmnNo”
c) AdmNo
d) “AdmNo”

Answer : c
83

SNO NAME OF THE KV TOPIC ALLOTTED


TEACHER

10 Mr ANAND NO2 CSV file: import csv module, open / close csv file,
GANESH GOLKONDA write into a csv file using csv.writerow() and read
from a csv file using csv.reader( )

MULTIPLE CHOICE QUESTIONS

1
The character that separates values in csv files is called the ………

a) delimit

b) delimiter

c) delimited

d) delimits

Ans: b)

2
The default delimiter of csv file is ……………

a) comma

b) colon

c) semicolon

d) hyphen

Ans:a)

3
The file mode to open a csv file for reading as well writing is ………

a) r

b) rw

c) r+

d) rb

Ans: c
84

4
The file mode to open a csv file for appending as well reading is ……..

a) w

b) w+

c) a

d) a+

Ans: d

5
To specify a different delimiter while writing into csv file, ……. argument is used with
csv.writer().

a) delimit

b) delimiter

c) delimited

d) delimits

Ans: b

6
To cancel the EOL translation in csv file while writing the data ………… argument is used
with open().

a) newline

b) next

c) open

d) EOL

Ans: a

7
To add data to an existing csv file, the mode of the file should be ……..

a) w

b) w+

c) a

d) a+
85

Ans: c

8
CSV stands for …….

a) Cursor Separated Variables

b) Comma Separated Values

c) Cursor Separated Values

d) Cursor Separated Version

Ans: b

9
Which module is used for working with CSV files in Python?

a) random

b) statistics

c) csv

d) math

Ans: c

10 Every record in a CSV file is stored in reader object in the form of a list using which
method?

a) writer()

b) append()

c) reader()

d) list()

Ans: c

CASE STUDY QUESTIONS (R)


1
Deepesh works as a programmer with Delta Technologies. He has been assigned the job
of generating the salary of all employees using the file “employee.csv”. He has written a
86

program to read the CSV file “employee.csv” which will contain details of all the
employees. He has written the following code. As a programmer, help him to successfully
execute the given task.

import______ # Line 1
def readCsvEmp( ): # to read data from the CSV file
with ______('employees.csv', newline='') as f: # Line 2

reader = csv.______ (f) # Line 3

data_list = ______(reader) # Line 4

______ (data_list) # Line 5

(a) Name the module he should import in Line 1.


1. import csv

2. csv import

3. import

4. export csv

Ans. 1. import csv


(b) Write the method that he should use to open the file to read data from it.
1. read

2. open

3. close

4. append

Ans.2. open
(c) Fill in the blank in Line 3 to read the data from a csv file.

1. read

2. readline

3. reader
87

4. writer

Ans.3. reader
(d) Fill in the blank in Line 4 with the method to convert the data read from the file into list.

1. list

2. sets

3. dictionary

4. tuple

Ans.1. list

2 Observe the following code and fill the blank in statement1


import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4

a. open("data.csv")
b. f=open("data.csv")
c. Both A & B are Correct
d. Both A & B are incorrect

Ans:a. open("data.csv")

3 Observe the following code and fill the blank in statement2


import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4

a. load
b. read()
c. reader()
d. readlines()

Ans: c. reader()

4
Observe the following code and fill the blank in statement3
88

import csv

with _________ as f: #statement1

r = csv.______(f) #statement2

for row in ______: #statement3

print(_____) #statement4

a. F

b. r

c. r,f

d. None of the above

Ans: b. r

5 Observe the following code and fill the blank in statement4


import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4

a. r
b. row
c. f
d. csv

Ans:b. row

6
Legend sports wanted to store the number of prizes for each sport as a SPORTS.CSV file.

As a programmer help them to complete the task successfully.

import _______________ #Line 1

fh=___________________ # Line 2

swriter = ______________(fh) #Line 3

ans=‟y‟

i=1
89

while ans==‟y‟:

print(“Record”,i)

sport=input(“Sport name”)

prizes=int(input(“Enter prizes won”))

__________ # Line 4

i=i+1

ans=input(“Want to enter records”)

fh._________________#Line 5

a) Name the module to be imported in Line 1.

1. .tsv
2. .csv
3. .py
4. .bin

Ans: 2. csv

b) Fill in line 2 to open the CSV file.

1. fh = open(“sports.csv”,”w”)

2. read(“sports.csv”,”w”)

3. fh = file(“sports.csv”,”w”)

4. fh = append(“sports.csv”,”w”)

Ans: 1. fh = open(“sports.csv”,”w”)
90

c) Write the correct statement to write the data into file in line 3.

1. writerows( )

2. writerow( )

3. writer( )

4. swriter = csv.csvwriter(fh)

Ans:4. swriter = csv.csvwriter(fh)

d) Write the statement to write the records given as input from user in line 4.

1. swriter([sport,prizes])

2. swriter.writrrow([sport,prizes])

3. swriter_writrrow([sport,prizes])

4. swriterwritrrow([sport,prizes])

Ans: 2. swriter.writrrow([sport,prizes])

7
Krishna of class 12 is writing a program to read the details of Sports

performance and store in the csv file “Sports.csv” delimited with a tab

character. As a programmer, help him to achieve the task.

import ___________ # Line 1

f = open(“Sports.csv”,”a”)

wobj = csv.______________ (f, delimiter = „\t‟) # Line 2

wobj.writerow( [„Sport‟, „Competitions‟, „Prizes Won‟] )

ans = „y‟
91

i=1

while ans == „y‟:

print(“Record :”, i)

sport = input(“Sport Name :”)

comp = int(input(“No. of competitions participated :”))

prize = int(input(“Prizes won:”))

record = ____________________ # Line 3

wobj.______________ (rec) # Line 4

i += 1

ans = input(“Do u want to continue ? (y/n) :”)

f.___________ # Line 5

a) Name the module he should import in Line 1

1. tcs

2. tmp

3. bin

4. csv

Ans : 4. Csv

b) To create an object to enable to write in the csv file in Line 2

1. open

2. writer

3. file

4. read
92

Ans : 2. writer

c) To create a sequence of user data in Line 3

1. [prize,comp,sport]

2. [comp,prize,sport]

3. [sport, comp, prize]

4. none of the above

Ans: 3. [sport, comp, prize]

d) To write a record onto the writer object in Line 4

1. write

2. writerow

3. writeline

4. writelines

Ans: 2. writerow

8
Kumar is writing a program to create a CSV file “student.csv” which will contain rollno,
name and age of some students. He has written the following code. As a programmer,
help him to successfully execute the given task

import ________________ # Line 1

f=open('student.csv','w',newline="")

p=csv._________(f) # Line 2

ch='y'

while ch=='y':

l=[]
93

rollno=int(input('enter rollno'))

name=input('enter name')

age=int(input('enter age'))

l.append(rollno)

l.append(name)

l.append(age)

p.___________(l) # Line 3

ch = input ('want to continue y/n?')

if ch=='y':

continue

else:

break

f.__________()

f=open('student.csv','r+')

c=list(csv.reader(f))

for i in c:

k=i[2]

if int(k)>15:

print(i)

f.close()

(a) Name the module he should import in Line 1

1. import csv

2. csv import

3. import

4. export csv

Ans. 1. import csv


94

(b) which function is used in Line 2 to create a writer object

1. p=tsv.writer(f)

2. p=psv.writer(f)

3. p=csv.writer(f)

4. p=dsv.writer(f)

Ans : 3. p=csv.writer(f)

(c) The method which is to be used in line 3 to writes a row of data into the specified file

1. p.writerow(l)

2. p.writerows(l)

3 p.writer()

4. p.writerow(l)

Ans:4. p.writerow(l)

(d) Fill in the blank in Line 4 to close the file.

1. f.close()

2. f.open()

3. close.f()

4. f.read()

Ans: 1. f.close()

9
Puneeta is storing the data of her gift store in a csv file named gift.csv which will
store Gift_code and Gift_name of items of her gift store. She has written the
following code .As a programmer help her to successfully execute her program in
python:

import ___________ # Line 1

def writeFile(Gift_code,Gift_name):

F=open(“gift.csv”,‟___‟) #Line 2

FW=csv.________(F) #Line 3

FW.writerow([Gift_code,Gift_name)
95

F.close()

#CSV file for reading

def readFile():

with ________(„gift.csv‟,‟r‟) as newF #Line 4

FR=csv.reader(newF)

for row in FR:

if row[0]==101:

print(row)

newF.close()

writeFile(101,”Photoframe”)

writeFile(102,”Soft Toys”)

writeFile(103,”Flower Pot”)

readFile() #Line 5

a) Name the module she should import in line 1.

1. .tmp

2. .bin

3. .tsc

4. .csv

Ans: 4. csv

b) In which mode Puneeta should open the file to add data in it?

1. „a‟

2. „ab‟

3. „r‟

4. „w‟

Ans: 1. „a‟

c) Fill in the blanks in Line 3 to write data to csv file gift.csv


96

1. close()

2. open()

3. writer()

4. append()

Ans: 3. writer()

d) Fill in the blank in Line 4 to open the csv file from the disk

1. close

2. open

3. write

4. read

Ans: 2. open

10
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

mumbai,andheri
1. Chennai,mylapore
2. mumbai,andheri
3. chennai,mumba
4. chennai,mylapore mumbai,andheri

Ans: 2. mumbai,andheri
97
98
99
100
101
102
103
104
105
106
107
108
109

You might also like