MCQ Questions Agra
MCQ Questions Agra
MCQ Questions Agra
Class XII
COMPUTER SCIENCE (083)
Session 2021-22
Sh. M.L.Mishra
Assistant Commissioner
KVS RO Agra Region
Co-ordinator
Mrs. Neetu Verma
Principal
K.V. NO. 3 Agra
TERM – 1
Syllabus
CLASS XII
Session : 2021-22
Programming - 2
Total 35
Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default
parameters, positional parameters, function returning value(s), flow of execution, scope
of a variable (global scope, local scope)
Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute
paths
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, writing/appending data to a text file using write() and
writelines(), reading from a text file using read(), readline() and readlines(), seek and tell
methods, manipulation of data in a text file
Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+,
ab, ab+), close a binary file, import pickle module, dump() and load() method, read,
write/create, search, append and update operations in a binary file CSV file: import csv
module, open / close csv file, write into a csv file using csv.writerow() and read from a csv
file using csv.reader( )
Revision of Python
Token : Smallest Individual unit in a program is known as Token. Python has following tokens:
Keywords
Identifiers
Literals
Operators
Keywords : Keywords are the words that have special meaning reserved by programming
language. They are reserved for special purpose and cannot be used for normal identifier names.
E.g. in, if, break, class, and, continue, True, False.
Identifiers : Dentifiers are fundamental building block of a program. They are names given to
variable, functions, objects classes etc. Python is case sensitive i.e. it treats upper case and lower
case letter differently.
Naming Conventions:
Literals : Literals are data items that have fixed value. Python allows several kinds of literals:
• String literals
• Numeric literals
• Boolean literals
• Complex Number: are in form a+bj, where a and b are floating point numbers and
j is
√-1. Where a is real part and b is imaginary part.
Operators:
Operators are the symbol, which triggers some computation when applied on operand.
• Unary Plus +
• Unary Minus –
• Bitwise ~ Complement
Punctuators : are the symbols used in programming language to organise the statements of the
program.
Identifier :
Named Label whose value can be changed and processed during the program run
• Creating Variable :
Name=„Anant‟
Age=30
• Python do not have fixed memory locations, when the value changes they change
their location
• The process in which the variable pointing to a value of certain type,can be made to
point to the value of other type.
age=10 print(age)
age=“ten”
print(age)
Dynamic Typing:
In Dynamic Typing the datatype attached with the variable can change during the program run
whereas in Static Typing the data type defined for the first time is fixed for the variable.
x = y = z = 20
x , y , z = 20, 40, 60
• input( ): function is used for taking value for a variable during runtime.
• To overcome the above error we need to convert the string type object to integer or
any desired numeric type.
• Use int( ) or float( ) function to convert the type string to int and float respectively.
• When converting variable to int/float we need to make sure that the value entered is
of int/float type.
• If we enter rashmi for age then rashmi cannot be converted to int.print statement has
number of features
Automatic conversion of items to string type. Inserting space between items automatically as
default value of sep (separator) is space. It appends a newline at the end of the each print
Data Types : Python offers five built-in core data types
• String
• List
• Tuples
• Dictionary
Integers
Complex Numbers: Python represents complex numbers as a pair of floating point numbers. E.g.
A+Bj. J is used as the imaginary part which has value √-1.
String:
• It can hold any type of known characters like alphabets, numbers, special characters
etc.
Forward Indexing
Backward Indexing
name=„hello‟
name*2+=„g‟ name=„Computer‟
# Not Possible
List: List in Python represents a list of comma-separated values of any data type between square
brackets. Mutable Data Type [1,2,3,4,5]
Tuples:In Python represents a list of comma-separated values of any data type between round
brackets. Immutable Data Type
Dictionary: in Python represents unordered set of comma-separated key : value pair within { },
with the requirement that within a dictionary, no two keys can be the same.
A={a‟:1, „b‟:2,‟c‟:3,‟d‟:4}
The immutable types: are those that can never change their value inplace.Immutable Data Types
are
– Integer
– Boolean
– String
– Tuples
Mutable types : are those whose values can be changed in place. Mutable Data Types are :
– List
– Dictionary
– Sets
Thus Mutability means that in the same memory address, new value can be stored as and when
you want.
Expression:
• Atoms are something which has value. E.g. Literals, identifier, string, list, tuples, sets
and dictionary etc.
• Types of Expression
During evaluation if the operands are of same data type then the resultant will be of the data
type which is common.
• Incase, during evaluation if the operand are of different data type then the resultant
will be of the data type of the largest operand. We need to promote all the operand
to the largest type through type promotion.
• Division operator will result in floating point number, even if both operands are
integer type.
• Python internally changes the data type of some oper and, so that all oper and have
same data type. This is called Implicit Type Conversion.
Explicit Type Conversion/Type Casting : user defined conversion that forces an expression to be
of specific type.
• Amt= int(amount)
Statement : Smallest executable unit of the program. These are instructions given to the
computer to perform any kind of action, data movement, decision making, repeating actions etc.
They are of three types
o Header line : It begins with the keyword and ends with a colon.
o Body : consist of one or more Python statements, indented inside header line. All
Statement are at same level of indentation.
In Python, if Statement is used for decision making. It will run the body of code only when IF
statement is true. When you want to justify one condition while the other condition is not true,
then you use "if statement".
Syntax:
if expression
Statement
Example:
a = 33
b = 200
if b > a:
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
else:
print(“a is greater than b")
By using "elif" : condition, you are telling the program to print out the third condition or
possibility when the other condition goes wrong or incorrect.
x,y =8,8
elif (x == y):
else:
print(st)
Loop:
• Loops can execute a block of code number of times until a certain condition is met.
Their usage is fairly common in programming. Unlike other programming language
that have For Loop, while loop, do while, etc.
o The range( ) function of Python generates a list which is special sequence type.
– range( lower limit, upper limit, step value) range( l, u, s) will give l, l+s, l+2s………….u-1
range(3,17,3) will give 3,6,9,12,15 range(13,7,2) will give 13,11,9,7
– Range(number)
in operator tests if a given value is contained in a sequence or not and return True or False.
Syntax:
for<variable> in <sequence>:
statements to repeat
Example:
Syntax:
while <logical expression> :
loop body
1. Initialization
2. Test Expression
4. Update Expression
Both the loops of Python has else clause. The else of a loop executes only when the loop end
normally( i.e. only when the loop is ending because the while loop’s test condition has become
false and for loop has executed the last sequence)
Jump Satement:
• The break statement in Python terminates the current loop and resumes execution at
the next.
• The continue statement in Python returns the control to the beginning of the while
loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
fees=__________________________
location=__________________________
if location == "Noida":
print ("I’ll take it!") #Statement 1
else:
elif fees<=25000:
else:
On the basis of the above code, choose the right statement which will be executed when different
inputs for pay and location are given.
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4
a. Statement 2
b. Statement 4
c. Statement 5
d. Statement 6
Correct Ans: Statement 6
a. Statement 1
b. Statement 2
c. Statement 4
d. Statement 6
a. Statement 6
b. Statement 5
c. Statement 4
d. Statement 3
a. Statement 2
b. Statement 3
c. Statement 4
d. Statement 5
Q2. Reema write the following program for generating the random number by writing the
following program but the program is not executed. Help her to correct the program:
AR=[20,30,40,50,60,70];
On the basis of the above code, choose the right option which will be executed when program
executed:
(i) She is getting the error “NameError: name 'random' is not defined”, while executing the
program to remove the above error she must use the option:
a. import random
b. random.h
c. import.random
d. random.random
(ii) What possible outputs(s) are expected to be displayed on screen at the time of execution of
the program.
10#40#70#
30#40#50#
50#60#70#
40#50#70#
(iii) What are the maximum values that can be assigned to each of the variables Lower and
Upper?
1,4
3,4
2,3
1,2
True
False
1,4
3,4
2,3
1,2
Q3. Priyank is a software developer with a reputed firm. He has been given the task to
computerize the operations for which he is developing a form which will accept customer data
as follows:The DATA TO BE ENTERED IS :
a. Name
b. Age
d. Bill amount
(i) Choose the most appropriate data type to store the above information in the given sequence.
(ii) Choose the correct varaible names to store the above information in the given sequence.
a. 2name,age,_items,bill amount
b. Name,_age,items,bill_amount
c. Name,4age,.items, bill@amount
d. Name,age,items,bill.amount
(iii) Now the data of each customer needs to be organized such that the customer can be
identified by name followed by the age, item list and bill amount. Choose the appropriate data
type that will help Priyank accomplish this task.
a. List
b. Dictionary
c. Nested Dictionary
d. Tuple
a. 16
b. 32
c. 64
(v) After completing the code Priyank want to save the program in which extension he will save
the Python file?
a. .py
b. .python
c. .p
d. None of these
Q4. Rohan create a Password validation program in Python. He has following conditions for a
valid password are:
SpecialSym=['$','@','#','%']
val = True
if len(passwd) < 6:
val = False
val = False
val = False
val = False
val = False
val = False
if (val==True):
else:
print("Invalid Password !!") # Statement 8
a. Only Statement 8
b. Statement 5, Statement 2
d. Statement 4, Statement 8
a. Only Statement 7
c. Statement 4, Statement 8
d. Statement 5, Statement 7
(iii) If Rohan wants to give three chances for the valid password to the user:
a. True
b. False
Correct Ans : a. True
Q5. Kritiks write a Python program which iterates the integers from 1 to 50. For multiples of three
print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which
are multiples of both three and five print "FizzBuzz". Help her to complete the following code
Code:
forfizzbuzzinrange(___): # Statement 1
if____________________________________://statement2
print("fizzbuzz")
continue
elif fizzbuzz%3==0:
print("fizz")
continue
elif fizzbuzz%5==0:
print("buzz")
continue
print(fizzbuzz)
(i) Which of the following command id used to generate the integer from 1 to 50 in statement 1?
a. range(1,51)
b. range(50)
c. range(1,50)
d. range(52)
c. Nothing
(iii) Which of the following command used to check the number is divisible by 3 and 5 in
statement 2
b. fizzbuzz % 3 == 0 or fizzbuzz % 5 == 0
a. 50
b. 51
c. 52
d. 27
Correct Ans: a. 50
String:-
String is a sequence of characters, which is enclosed between either single (' ') or double
quotes (" "), python treats both single and double quotes same.
Creating string:-
b=input(“Enter string”)
String slicing:
It refers to part of string containing some contiguous character from the string.
e.g.
Each character of the string can be accessed one character at a time using for loop.
Eg :
code='Computer Science‘
for i in code:
print(i, end=” “) c o m p u t e r
Operations in String
in Membershipcheck pinawillgive1
LIST-
The list is a collection of items of different data types. It is an ordered sequence of items
Each element of a sequence is assigned a number - its position or index. The first index is zero,
the second index is one, and so forth.
The values that make up a list are called its elements. Elements are separated by comma and
enclosed in square brackets [].
Syntax of List
Lists
Declaring/Creating Lists
Traversing a List
Aliasing
Comparing Lists
Slicing
Opeartion on Lists-
Python Expression Results Exp’computlanation
print x,
Nested Lists:-
L3=3,4,[5,6,7],8]
A list can have an element in it, which itself is a list. Such a list is called a nested list
Built in Functions:
Tuple:- Tuple is a collection of values separated by comma and enclosed in parenthesis. Unlike
lists, tuples are immutable
Creation of Tuple:
Accessing a Tuple
Tuple Operations
Tuple Slicing
Dictionary:
Unlike lists, dictionaries are inherently order less. The key: value pairs appear to be in a certain
order but it is irrelevant.
Each KEY must be unique, but the VALUES may be the same for two or more keys.
If you assign a value to a key then later in the same dictionary have the same key assigned to a
new value, the previous value will be overwritten.
Instead of using a number to index the items (as you would in a list), you must use the specific
key.
CASE - BASED MCQ
Question1 : Naman prepare a code for different conditions and take different inputs in variable
str1. What will be the output for the different inputs given below:
str1="PT1"
str2=" "
I=0
while I<len(str1):
if str1[I]>="A" and str1[I]<="M":
str2=str2+str1[I+1]
elif str1[I]>="0" and str1[I]<="9":
str2=str2+str1[I-1]
else:
str2=str2+"*"
I=I+1
print(str2)
a. X***M202 b. X**M2021
c. x***m201 d. x***m202
a. Bs*-*x*** b. BS*-*x***
c. BS*-*x** d. BS**-*x**
Ans:- b. BS*-*x***
a. **T b. *T*
c. T** d. **
Ans- c. T**
a. **A b. ***A
c. *xyz d. Error : String index out of range
Question 2 : Assume, you are given two lists: a = [1,2,3,4,5] b = [6,7,8,9] The task is to create a
list which has all the elements of a and b in one dimension.
(i) If Output : a = [1,2,3,4,5,6,7,8,9] , Which of the following option would you choose?
a. a.append(b) b. a.extend(b)
Ans:-b. a.extend(b)
(ii) If Output : a = [1,2,3,4,5,[6,7,8,9]] , Which of the following option would you choose?
Ans:-. a.append(b)
(iii)You want to update the value of this lista = [1,2,3,4,5] at 4th index to 10. Which of the
following option will you choose?
a. a(4) = 10 b. a[4] = 10
Ans:-b. tup[4] = 10
(iv)You want to insert the value 100 at 2nd index. Which of the following option will you choose?
Ans:-a.insert(2, 100)
Question3: Suppose you are defining a tuple given below: tup = (1, 2, 3, 4, 5 )
(i) You want to update the value of this tuple at 2nd index to 10. Which of the following option
will you choose?
a. tup(2) = 10 b. tup[2] = 10
(ii) You want to check the index of value 5. Which of the following option will you choose?
a. tup.index(5) b. tup=index(5)
c. tup.index(4) d. tup=index(4)
Ans:-tup.index(5)
(iii) You want to check the minimum value of tup. Which of the following option will you choose?
a. min=tup() b. tup=min(1)
c. tup=min() d. min(tup)
Ans:- d. min(tup)
(iv) You want to check the length of tup. Which of the following option will you choose?
a. len.tup b. len(tup)
Ans:- b. len(tup)
(v) You want to delete tup. Which of the following option will you choose?
a. delete(tup) b. remove(tup)
Ans:-del tup
FUNCTION
Functions are the most important building blocks for any application in python and work on the
divide and conquer approach.
A function is a sub program of a large program/application that accept some data and return a
value, where each function performing a specific tasks.
The use of functions makes a program easy to Read, Write, Understand, Manage and Debug.
Functions are line of codes that executed sequentially from top to bottom by the python
interpreter.
A Python function is written once but can be called any number of times.
Built-in Functions:
Functions in Modules:
User-defined Functions:
User Defined Functions are the functions created or defined by the user using “def” (keyword)
statement followed by Function name and Parenthesis.
-----------------------------------
return <value> # here return is a keyword
Example:
area_of_circle(r)
output:
Every function header end with parenthesis and colon sign followed by function name
The return statement is used to return a value from function. The return statement is also
optional. The function should return a value only at the place from where it get’s called.
3.Functions which do not accept any argument but return some value
4.Functions which do not accept any argument and even not return any value
Parameters/Arguments passed to functions: These are the values passed to user defined
functions from the calling function.
If you are passing values of immutable types (i.e., numbers, strings,etc) to the Called function,
then the called function cannot alter their values.
If you are passing values of mutable types (i.e., List, Dictionary, etc) to the Called function, then
the called function can make changes to them.
Formal Parameters or Formal Arguments: These are the values provided in Parenthesis when we
write a function Header.
Actual Parameters or Actual Arguments: These are the values passed to the function when it is
called/invoked.
Example:
def area_of_circle( radius ): # here radius is the Formal Parameter or Formal Argument
output:
Types of Arguments:
Positional Arguments
Default Arguments
Keyword Arguments
The return statement in python specifies what value to be returned back to the calling function.
The Functions can take input values as parameters, process them and return output to the calling
function.
In python the return statement can return one or more values at a time.
If the return statement is without an expression, the special value None is returned.
The function will return None in case we don’t explicitly give a return statement in function.
Example:
if X>Y:
return X
else:
return Y
Output:
Maximum value = 56
1. Mohit class XII student has designed following code, which showing no error but gives no
output after executing the code. Suggest the correct solutions to his problem out of the
following.
A program to calculate simple interest:
def simple_int(p,r,t):
si=(p*r*t)/100
print(“Simple interest = “, simple_int(5000,10.5,2))
(a) function should print the value of simple interest no need to return
(b) function should return the value of si
(c) the formula used in function gives no output
(d) both (a) & (b)
ANSWER: (b) function should return the value of si
2. Assertion (A): All the functions are called user defined functions to perform a particular
task.
Reason (R): Functions are defined by the user to perform a particular task.
(a) Both A and R are true and R is the Correct reason of A
(b) Both A and R are false
(c) A is true but R is false
(d) A is false but R is true
ANSWER: (b) Both A and R is false
3. Rohan is solving a sample question paper provided by board, the sample question paper
contain a code having blank lines and options for the user to complete the code. Kindly
go through the following code and choose correct option for the statement1, 2 & 3.
----------------------------------- # statement1
def area_of_circle(radius):
area=pi*radius**2
-------------------------------- # statement2
STANDARD
USER DEFINED
LIBRARY
FUNCTIONS
FUNCTIONS
BUILT IN
MODULES
FUNCTIONS
The Python has a number of built-in functions. They are loaded automatically as a shell starts
and are always available, such as
max( x, y, z, .... ) It returns the largest of its >>>max(80, 100, 1000) 1000
arguments: where x, y and z are >>>max(-80, -20, -10) -10
numeric variable/expression.
min( x, y, z, .... ) It returns the smallest of its >>> min(80, 100, 1000) 80 >>>
arguments; where x, y, and z are min(-80, -20, -10) -80
numeric variable/expression.
cmp( x, y ) It returns the sign of the difference >>>cmp(80, 100) -1
of two numbers: -1 if x < y, 0 if x == >>>cmp(180, 100) 1
y, or 1 if x > y, where x and y are
numeric variable/expression.
divmod (x,y ) Returns both quotient and >>> divmod (14,5) (2,4) >>>
remainder by division through a divmod (2.7, 1.5) (1.0,
tuple, when x is divided by y; where 1.20000)
x & y are variable/expression.
len (s) Return the length (the number of >>> a= [1,2,3] >>>len (a) 3 >>>
items) of an object. The argument b= „Hello‟ >>> len (b) 5
may be a sequence (string, tuple or
list) or a mapping (dictionary).
Apart from these functions, you have already seen the use of the following functions:
Module
In addition to built-in functions, a large number of pre-defined functions are also available as a
part of libraries bundled with Python distributions. These functions are defined in modules. While
a function is a grouping of instructions, a module is a grouping of functions. A module is created
as a python (.py) file containing a collection of function definitions.
There are two ways to import a module in our program, they are
Import: It is simplest and most common way to use modules in our code.
Syntax:
Example: Input any number and to find square and square root.
import math
y = math.sqrt(x)
a = math.pow(x,2)
output:
From statement: It is used to get a specific function instead of complete file. If we know
beforehand which function(s), we will need, then we may use 'from'. For modules having large
number of functions, it is recommended to use from instead of import.
Syntax
Example: Input any number and to find square and square root.
Some of the other modules, which you can explore, are: string, time, date.
Note:
• import statement can be written anywhere in the program
• In order to get a list of modules available in Python, we can use the following statement: >>>
help("module")
Execution always begins at the first statement of the program. Statements are executed one at a
time, in order from top to bottom. Function definition does not alter the flow of execution of
program, as the statement inside the function is not executed until the function is called.
On a function call, instead of going to the next statement of program, the control jumps
to the body of the function; executes all statements of the function in the order from top to
bottom and then comes back to the point where it left off. This remains simple, till a function
does not call another function. Simillarly, in the middle of a function, program might have to
execute statements of the other function and so on.
It is also important to note that a function must be defined before its call within a program.
Below example program explains the flow of execution for a programs. The number in square
brackets shows the order of execution of the statements.
Example 1:
[4] print("Thanks")
Example 2:
[7] print(Area)
[8] print("thanks")
Scope of Variables
VARIABLE
SCOPE
LOCAL GLOBAL
SCOPE SCOPE
Scope of variable refers to the part of the program, where it is visible, i.e., area where you can
refer (use) it.
We will study two types of scope of variables- global scope or local scope.
Global Scope
A variable, with global scope can be used anywhere in the program. It can be created by defining
a variable outside the scope of any function/block.
Example
x=40
def func ( ):
Inside func x is 40
Value of x is 40
Any modification to global is permanent and visible to all the functions written in the file.
Example
x=40
def func ( ):
x+= 10
will produce
Inside func x is 50
Value of x is 50
Local Scope
A variable with local scope can be accessed only within the function/block that it is created in.
When a variable is created inside the function/block, the variable becomes local to it. A local
variable only exists while the function is executing.
Example
X=40
def func ( ):
y = 20
print (“Value of x is ‟, X, “; y is ‟ , y )
print (“Value of x is ‟, X, “ y is “ , y)
Value of x is 40; y is 20
The next print statement will produce an error, because the variable y is not accessible outside
the function body.
A global variable remains global, till it is not recreated inside the function/block.
Example
x=40
def func ( ):
x=4
y=2
If we want to refer to global variable inside the function then keyword global will be
Example :
x=40
def test ( ):
global x
x =2
y=2
Answer.a
Q2. A local variable having the same name as that of a global variable, hides the global variable
in its function.
(a) True
(b) False
Answer.a
Q3. The _____ refers to the order in which statements are executed during a program run.
Answer.a
Q4. A _____ is a file containing Python definitions and statements intended for use in other
Python programs.
(a) Function
(b) Module
(c) File
(d) Package
Answer.b
Answer : A
Q6. Assertion (A): sqrt() is used to calculate square root but can not directly used in Python codes.
Answer. A
Q7 . Assertion (A): len() can be directly accessed in Python codes.
Answer. A
Q8. Assertion (A): Function definition does not alter the flow of execution of program.
Reason(R): Statement inside the function is not executed until the function is called.
Answer. A
a) Custom function
c) User function
d) System function
Answer: b
Explanation: Built-in functions and user defined ones. The built-in functions are part of the
Python language. Examples are: dir(), len() or abs(). The user defined functions are functions
created with the def keyword.
b) Class
c) Another function
Answer: d
a) Module
b) Class
c) Another function
Answer: d
Introduction to file:
A file is a packet in which any information or logically related data is stored with a unique identity
name. A file can have the information like textual, audio, video, image etc.
Classification of file:
A file classification scheme (also known as a file plan) is a tool that allows for identifying, titling,
accessing and retrieving records of a file by the help of file extension.
Text files:
(i) All the information in text files are saved in the format of ASCII codes.
(iii) All the lines in the text files terminated by a special syntax classed "\n" (new line).It is also
known as End of Line (EOL).
(vi)All the data of text file is displayed in the same fashion as it is stored in the memory.
Binary files:
(v) All the data of binary file is displayed in the different fashion, while it is stored in the binary
format in the memory.
(vi) The Image, Audio and Video files are the example of Binary files.
(i) A CSV file stores the in tabular data (numbers and text) in plain text.
(iii) It stores the data in tabular format, also known as a spreadsheet or database.
Q.1Avni is a class XII Computer Science student studying Data File Handling chapter. She has gone
through the basics of file systems. She is having some questions after reading the book contents.
Help het to find the correct answers.
(c) Avni makes a lesson note using an application and stored with the file extension (.docx), On
which application she has made her lesson note.
(d)Avni is taking some pictures of her notes, which extension will the files be used to store?
(i)JPG (ii)JPEG/JPG
(iii)TXT (iv)MP4
Answer Keys:- (a) (iv) All of the above (b) (i) File Extensions (c) (ii) MS Word
Q.2 Rajat, a class XII computer science student is working on text file. Help him to find the answers
of his some questions/doubts…
(d)Each line of a text file is terminated with a special name and symbol…….
(e) Files having information related audio & video comes under the categories of ……
(f) Which file system stores data in tabular format,in Data file handling?
Answer Keys:- (a) (ii) Interchange Information (b) (i) 1- Byte (8-bits) (c) (iii) Option (i)
& (ii)
(d) (iv)All of these (e) (i) Binary files (f) (iii)CSV files
(g) (iv) All of these (h) (i) A Row (Each line of data)
TEXT FILE HANDLING
A file is a named location on a secondary storage media where data is stored temporary or
permanently for later use. A text file can be understood as a sequence of characters consisting
of alphabets, numbers and other special symbols. Each line of a text file is terminated by a special
character, called the End of Line (EOL).
To open a text file in Python, we use the open() function. The syntax of open() is as follows:
(This function returns a file object called file handle which is stored in the variable file_object. If
the file does not exist, the above statement creates a new empty file and assigns it the name we
specify in the statement.)
The file_object has certain attributes that tells us basic information about the file, such
as:
<file.mode> returns the access mode in which the file was opened.
The access_mode is an optional argument that represents the mode in which the file has to be
accessed by the program. The default is the read mode.
close() function : Once we are done with the read/write operations on a file, it is a good practice
to close the file.
file_object.close()
Here, file_object is the object that was returned while opening the file. Python makes sure that
any unwritten or unsaved data is flushed off (written) to the file before it is closed.
FILES MODE: It defines how the file will be accessed:-
<rb> Opens the file in binary and read-only mode. Beginning of the file
<r+> or <+r> Opens the file in both read and write mode. Beginning of the file
Opens the file in write mode. If the file already exists, all
<w> the contents will be overwritten. If the file doesn’t exist, Beginning of the file
then a new file will be created.
<wb+> or Opens the file in read,write and binary mode. If the file
already exists, the contents will be overwritten. If the Beginning of the file
<+wb> file doesn’t exist, then a new file will be created.
In Python, we can also open a file using with clause. The syntax of with clause is:
The advantage of using with clause is that any file that is opened using this clause is closed
automatically, once the control comes outside the with clause.
Example:
content = myObject.read()
myobject.writelines(lines)
myobject.close()
We can write a program to read the contents of a file. Before reading a file, we must make sure
that the file is opened in “r”, “r+”, “w+” or “a+” mode.
Hello everyone
If no argument or a negative
number is specified in read(),
the entire file content is read. myobject=open("myfile.txt",'r')
print(myobject.read())
Hello everyone
myobject.close()
If no argument or a negative
number is specified, it reads a myobject=open("myfile.txt",'r')
complete line and returns
string. print(myobject.readline())
'Hello everyone\n'
readlines() <filehandle>.readlines() The method reads all the lines myobject=open("myfile.txt", 'r')
and returns the lines along
with newline as a list of print(myobject.readlines())['Hello
strings. everyone\n', 'Writing multiline
strings\n', 'This is the third line']
myobject.close()
Setting offsets In a File:
The functions that we have learnt till now are used to access the data sequentially from a file.
But if we want to access data in a random fashion, then Python gives us seek() and tell() functions
to do so.
print(f.readline())
The reference point is selected by
the from_what argument. It f.close()
accepts three values:
“ India is my country
I love my country,
a. f.read() b. f.readline()
f.readline() f.read()
f.readlines() f.readlines()
c. f.readline() d. f.readlines()
f.readline() f.readline()
f.readlines() f.readline()
Ans: c. f.readline()
f.readline()
f.readlines()
Q.2 Considering the content stored in file “PLEDGE.TXT”, write the output
f = open(“PLEDGE.TXT”)
print(f.read(2))
print(f.read(2))
print(f.read(4))
a. India b. In
is di
my a is
c. Ind d. India is my country
ia And all Indians are my brothers and sisters,
is I love my country,
Ans: b. In
di
a is
Q.3 Which of the following commands is used to write the list L into the text, POEM.TXTwith
file handle F ?
a. F.write(L) b.F.writeline(L)
c. F.writelines( ) d. F=write(L)
Ans c. F.writelines( )
Q.4 Which of the following statements correctly explain the function of tell() method?
c. indicates that the next read or write occurs from that position in a file.
Q.5 In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v) r+
vi) ab
vii) w+b
viii)wb
ix) w+
BINARY FILES
BINARY FILES
FOR READING/ WRITING
DATA IN THE FORM OF
BYTES FROM/TO FILE
Binary files use strings of type bytes. This means when reading binary data from a file, an object
of type bytes is returned.
Binary files are also stored (written) in terms of bytes (0s and 1s), but unlike text files, these bytes
do not represent the ASCII values of character.
Rather, they represent the actual content such as image, audio, video, compressed versions of
other files, executable files, etc.
Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents. Thus, trying to open a binary file using a text editor will show
some garbage values.
Pickle module converts Python object to byte stream so that it can be stored on disk. This process
is called Pickling.
While retrieving data from file Pickle module converts stream of bytes to original structure. This
process is called Unpickling.
Process the data in a loop ie repeat the step 4 and step 5 for all records
Read data from the file (in a variable say d) using load( fileobject) method
Apply appropriate search function / method on the variable read from the file.
Close file
Close file .
3. Read data from the file (in a variable) using load() method
Example 1: #Create a binary file "emp.dat" that writes n employee records in the file with details-
[empno, ename, sal] and then read the contents from the file
import pickle
f=open("emp.dat", "wb")
c='Y'
r=[n,nm,s]
pickle.dump(r,f)
f.close()
Example 2 :: Write a function search_cd(n) that takes a parameter ie name of cd and searches for
the quantity of it in the file "Audio.dat" containing records of the format- [CdNo, CD name, Qty]
import pickle
def search_cd(n):
f=open("Audio.dat","rb")
fl=0
while True:
try:
r=pickle.load(f)
if(r[1].lower()==n.lower()):
fl=-99
except EOFError:
break
if fl==0:
f.close()
return
1. add a record to the file having the record in the format - [Itemno, item name, price]
4. Update the price for a particular item name input by the user.
import pickle
def ins_rec():
f=open("item.dat","ab")
ino=input("Input Itemno::")
d=[ino,nam,pr]
pickle.dump(d,f)
f.close()
return
def search_rec():
f=open("item.dat","rb")
fl=0
n=input("Enter item name to b searched::")
while True:
try:
r=pickle.load(f)
if(r[1]==n):
fl=-99
except EOFError:
break
if fl==0:
f.close()
return
def disp():
f=open("item.dat","rb")
i=0
while True:
try:
r=pickle.load(f)
i=i+1
except EOFError:
break
f.close()
return
def update_rec():
f=open("item.dat","rb+")
fd=0
fl=[]
while True:
try:
r=pickle.load(f)
fl.append(r)
except EOFError:
break
f.close()
for x in fl:
#biscUITS
fd=1
x[2]=p
f=open("item.dat","wb")
for x in fl:
pickle.dump(x,f)
if fd==0:
f.close()
return
def del_rec(n):
f=open("item.dat","rb")
fd=0
fl=[]
while True:
try:
r=pickle.load(f)
fl.append(r)
except EOFError:
break
f.close()
f=open("item.dat","wb+")
for x in fl:
if n==x[0]:
fd=1
continue
pickle.dump(x,f)
if fd==0:
ch='Y'
print("Items DATA")
print("6. Exit")
if c==1:
ins_rec()
elif c==2:
search_rec()
elif c==3:
disp()
elif c==4:
update_rec()
elif c==5:
del_rec(n)
else:
break
Q1) Rashmi is eager to learn Python, and has learnt Python so far through videos, websites etc.
Now, she is writing her first program using binary files in which she is trying to record the
observation of various plants in her surrounding in the following format:
She has succeeded in writing partial code and is confused in certain statements, so she has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Rashmi.
___________ # Statement 1
def addPlants():
t=tuple()
f= _______ #Statement 2
while True:
____________ #Statement 3
____________ #Statement 4
break
f.close()
Answer any four questions (out of five) from the below mentioned questions.
i) Which of the following statement is correct to mention the module to be used for creating
binary file? ( Statement 1)
import csv
import files
import pickle
import binary
Correct Answer : c. import pickle
ii) Which of the following commands is used to open the file “MyPlants.DAT” for adding records
in binary format to previously existing plant data? (Statement 2)?
a. open("MyPlants.DAT",'wb')
b. open("MyPlants.DAT",'ab')
c. open("STUDENT.DAT",'a')
d. open("STUDENT.DAT",'r+')
iii) Which of the following commands is used to populate the tuple t for writing records into the
binary file, MyPlants.DAT? (marked as Statement 3)
iv) Which of the following commands is correct to write the tuple t into the binary file,
MyPlants.DAT? (Statement 4)
a. pickle.write(t,f)
b. pickle.load(t, f)
c. pickle.dump(t,f)
d. f=pickle.dump(t)
v) Read both the statements carefully and choose the correct alternative from the following :
b)A and R are both correct, but R is not the correct explanation of A.
Correct Answer : a. A and R are both correct, also R is the correct explanation of A.
Q 2) Ranjeet, is newly recruited in a Software Firm that designs software for Aerospace
manufacturers. He has been assigned a program for searching a record in a binary file
‘AircraftForces.dat’ that stores the data in the format given below :
He is successful in writing the partial code and has missed out certain statements, so he has left
queries in comment lines. You as an expert TeamLeader have to provide the missing statements:
def write_effect():
while True:
r=pickle.load(af)
else:
except EOFError:
break
f.close()
af.close()
return
#main program
In which mode Ranjeet should open the files Aircraft.dat in Statement 1 and ForceEffect.dat in
Statement-2?
a) wb and rb
b) rb and wb
c) ab and wb
d) r and w
ii) What will be the suitable code to be used in Statement 3 to avoid getting into an infinite loop?
for i in range(20):
try
if (af):
Break
a. ) if r[3]>r[5]
b) if(r[2]>r[4])
c) try
d) True
iv) Identify the correct statement among the following to write the data in file ‘ForceEffect.dat’
in the blank marked as Statement 5 and Statement 6?
v) Which statement among the following should be used in blank space in line marked Statement
7?
def write_rec()
func write_rec( )
call write_rec()
write_rec()
Q 3) Kaustubh is given an opportunity to work in a firm that designs software for stock market
analysis during internship on stipend. Now, he has been assigned a task to work on python binary
files on which he has little expertise.
ins_rec() : to add the records at the end of file stock.dat in the following format
He was successful in writing the program but after many attempts. He marked those statements
with blanks in which he tried various options to try again and again for practice. The options with
which he tried the code are listed as options with only one correct code statement using which
he was successful at last. Identify the correct option in questions given below
import pickle
def ins_rec(cid,d,o,h,l,c):
file_obj=___________ # statement 1
rec={}
rec["Comp_name"]=cid
rec["date"]=d
rec["open"]=o
rec["high"]=h
rec["low"]=l
rec["close"]=c
_________________ #Satement 2
file_obj.close()
return
def update_rec():
f=open("stock.dat","rb+")
fd=0
fl=[]
try:
while True:
r=________ # Statement 3
fl.append(r)
except EOFError:
pass
f.close()
print(fl)
for x in fl:
_________ # Statement 4
fd=1
x['high']=p
print(fl)
f=_________ # Statement 5
for x in fl:
pickle.dump(x,f)
if fd==0:
f.close()
return
i) In statement 1, he wanted to open the file ‘stock.dat’ to add records at the end of file. The
possibilities with which he tried the code are listed below and only one is correct with which the
code worked.
a) open("stock.dat","a")
b) open("stock.dat","ab")
c) open("stock.dat","a+")
d) open("stock.dat","wb")
Correct Answer : b) open("stock.dat","ab")
ii) Which option is correct among the following to be written as statement 2 to write the records
into the file stock.dat?
dump(rec,file_obj)
pickle.dump(file_obj, rec)
pickle.dump(rec,file_obj)
pickle.write(rec,file_obj)
iii) In statement 3, he wants to read a record from the file and tried with following statements.
Choose the one with which Kaustubh was successful.
pickle.load(f)
load(f)
read(f)
pickle.read(f)
iv) In Statement 4, he wants to compare the company name of the record read and the
company’s name entered by the user whose high is to be updated.
for k in x.values():
for k in x.keys():
if k in x.keys():
if x['Comp_name'].lower()==n.lower():
v) What will be the correct code for Statement 5 to open the file for writing the updated records
in the binary file after making all updations in list fl .
open("stock.dat","ab")
open("stock.dat","wb+")
open("stock.dat","wb")
open("stock.dat","w")
Q 4) Akhtar is a student and is assigned a program by his teacher to store the details of all his
classmates in a binary file ‘ClassXII_A.dat’ with the following record format:
delete_tc() :to search and delete the record with given admn no for TC students
The code is given below with few errors and blanks due to which he is unable to run the program
successfully. You, as an expert, help him run the program successfully by choosing the correct
option.
1 import pickle
2 def add_rec():
8 rec=[adm,sname,fname,phno]
9 pickle.dump(rec,file_obj)
10 return
11 def del_tc(n):
12 f=open("ClassXII_A.dat") # Statement 1
13 fd=0
14 fl=[]
15 try :
16 while True:
17 r=pickle.load(f)
18 fl.append(r)
19 except EOFError:
20 pass
21 f.close()
22 with open("ClassXII_A.dat","wb+") as f:
23 for x in fl:
24 ____________ #Statement 2
25 fd=1
27 pickle.dump(x,f)
28 if fd==0:
30 return
i) Akhtar has not closed the file in the function add_rec(). Identify the suitable option to close the
file.
file_ob.close()
pickle.close()
close(file_obj)
There is no need to close the file in this case as python will automatically close the file.
Correct Answer : d) There is no need to close the file in this case as python will automatically
close the file.
ii) In Statement 1 he wants to open the already existing file to read all the records and store
them in a list. When he is executing the program he is getting an error in statement1. Help him
diagnose the reason of error and correct code, by selecting the correct option below::
He is opening in reading mode, while he was supposed to open in writing mode to delete it,
f=open(“ClassXII_A.dat”,”wb”),
He is opening in reading mode, while he was supposed to open in writing mode to delete it,
pickle.open(“ClassXII_A.dat”,”wb”)
Correct Answer : c) He has not mentioned the binary mode, so he must write,
f=open(“pickle.dat”,”rb”)
iii) What should be written in Statement 2, line no 24 to compare the admission no sent as an
argument to function del_tc() with admission no present in list fl?
a) if n==x[0]:
b) while n==x[0]:
c) if n==x :
d) while n in x:
iv) In the block between line no 22 to 30, he is trying to skip the record from writing into the file
matched with admission no passed as an argument to del_tc() but is not successful in it. Identify
the correct statement and its position which could help him skip the record to be deleted from
writing into the file.
v) Which of the following statements correctly explain the operation performed by following
statement:
File_object. seek(35,1)
a) moves the current file position to 35 bytes forward from the end of file.
b) moves the current file position to 35 bytes backward from the end of file.
c) moves the current file position to 35 bytes forward from the current position in the file.
d) moves the current file position to 35 bytes forward from the beginning of file.
Correct Answer : c) moves the current file position to 35 bytes forward from the current
position in the file.
Q 5) Priyanka’s father owns a pharmacy shop. She is studying python in class XII. She decided to
computerize the data for her father’s shop with the help of binary files and storing the data in
the given format:
She has written the following code but is having difficulty in some statements. Help her solve the
errors:
import pickle
def ins_rec():
rec={ }
rec['Name']=mid
d=input("Enter Quantity::")
8. rec['Qty']=d
9. pickle.dump(rec,file_obj)
10. return
12. fd=0
13 lst=[]
15 try:
16 while True:
17 r=pickle.load(file_rw)
18 lst.append(r)
19 except EOFError:
20 pass
21 print(lst)
23 if ( lst[i]['Name']==nm):
24 fd=1
25 lst[i]['Qty']-=n
26 print(lst)
27 ________________
28 for x in lst:
29 ___________________
30 if fd==0:
32 return
33 def disp():
34 f=open("med_lab.dat","rb")
35 i=0
37 while True:
38 try:
39 r=pickle.load(f)
40 i=i+1
43 break
44 f.close()
45 return
46 ins_rec()
47 disp()
50 sell_med(n,q)
51 disp()
i) In line 14, she wants to open file for both reading and writing, help her right the correct
file access mode?
a) ‘w+’
b) ‘rb+
c) ‘ab+’
d) ‘rw’
Correct Answer : b) ‘rb+’
ii) She is trying to search medicine ‘Combiflam’, though it exists in file but
a) Line 23 as if ( lst[i]['Name'].lower()==nm.lower()):
c) Line 23 as if ( lst[i][0].lower()==nm.lower()):
d) Line 23 as if ( lst[i].lower()==nm.lower()):
iii) In line 25, she doubts there is an error, as when she is trying to subtract the required quantity
it shows typeError. Suggest a possible reason for it to her?
iv) In line 27, she is trying to reposition the file object to the beginning of the file to start writing
the modified records. Identify the correct option that will help Priyanka accomplish the task.
a) file_rw.open(‘ med_lab.dat’,”wb”)
b) file_rw.open(‘ med_lab.dat’,”wb”)
c) file_rw.tell(0)
d) file_rw.seek(0)
v) What should be the correct statement to be written in line no 29 to write the updated record
in the file?
a) file_rw.dump(x)
b) pickle.dump(x,file_rw)
c) pickle.dump(lst, file_rw)
d) file_rw.writelines(x)
Q6) Amritya Seth is a programmer, who has recently been given a task to write a python code to
perform the following binary file operations with the help of two user defined
functions/modules:
AddStudents() to create a binary file called STUDENT.DAT containing student information – roll
number, name and marks (out of 100) of each student.
GetStudents() to display the name and percentage of those students who have a percentage
greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent.
He has succeeded in writing partial code and has missed out certain statements, so he has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Amritya.
Answer any four questions (out of five) from the below mentioned questions.
import pickle
def AddStudents():
while True:
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
Countrec+=1
Total +=R[2]
Countabove75+=1
except:
break
if Countabove75==0:
average=Total/Countrec
Addstudents()
GetStudents()
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
ii) Which of the following commands is used to write the list L into the binary file, STUDENT.DAT?
(marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
Correct Answer : c. pickle.dump(L,F)
iii) Which of the following commands is used to read each record from the binary file
STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
iv) Which of the following statement(s) are correct regarding the file access Modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and
creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and
creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists.
Correct Answer : a
method?
c. indicates that the next read or write occurs from that position in a file.
Correct Answer : d
Q 7) Arun, during Practical Examination of Computer Science, has been assigned an incomplete
search() function to search in a pickled file student.dat. The File student.dat is created by his
Teacher and the following information is known about the file.
separate list of each student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of roll number 1.
def search():
f = open("student.dat",____ ) #Statement-1
……….. : #Statement-2
while True:
if(____): #Statement-4
print(rec)
except:
pass
____________ #Statement-5
a) r
b) r+
c) rb
d) wb
Correct Answer: c) rb
ii) Identify the suitable code to be used at blank space in line marked as Statement- 2
a. ) if(rec[0]==1)
b) for i in range(10)
c) try
d) pass
iii) Identify the function (with argument), to be used at blank space in line marked as Statement-
3.
a) load()
b) load(student.dat)
c) load(f)
d) load(fin)
IV ) What will be the suitable code for blank space in line marked as Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
d) rec[0]==1
V) Which statement Arun should use at blank space in line marked as Statement-4 to close the
file.
a) file.close()
b) close(file)
c) f.close()
d) close()
A CSV (Comma Separated Values) file is a simple plain text file having extension .csv.
Because it is a text file it only contains text data means ASCII / Unicode characters.
In CSV file data is stored in rows and columns form (tabular form).
The character that separates values is known as delimiter. Normally CSV files uses a comma to
separate each value but comma is not the only delimiter. We can also use tab ( ‘\t’ ), colon ( : ),
semi-colon ( ; ) or any other character.
OR
Here first row is the header holding the name of the columns and after that each row have a
separate record. We can easily notice that each piece of data is separated by a comma.
Text files have plain text without any format CSV files also have plain text but in a tabular
format ( rows / columns)
There is no concept of delimiter In csv file each row is considered as a record having
many fields. Fields are the values separated by
delimiter.
Text file can be opened in any text editor Csv files can be opened in any text editor as well
as in any spreadsheet.
csv.writer( ) : This function accepts the file object and returns a writer object that can be used to
write into a csv file.
writer_object.writerow( ) : This function is used to insert the record into the csv file. It requires
the record in the form of list or tuple.
for example :
The above program will create a file student.csv at e drive. A glimpse of the file is
Note : There is an empty line (or newline in terms of programming) after each row in the
student.csv file. To avoid this empty line we can override the newline as empty by adding a new
argument newline=’’ in the open ( ) function as follows
Sometimes while executing the file creation program again and again we encounter the following
error of Permission denied
The error may have occurred because the csv file is already open and we can’t write in an open
file. To avoid it just close the csv file and try again.
To write multiple rows or two dimensional list we can use writerows( ) function instead of
writerow( ) as follows
The content of the student.csv file will be the same as the above program. The only difference
here is that we are using writerows( ) function which can write multiple rows at a time.
To write a CSV file with any other delimiter like colon ( ‘:’ )
If we want to use any delimiter other than default delimiter that is comma ( , ) we simply have
to mention delimiter argument while creating the writer object using the writer( ) function as
shown below:
We can easily notice that here each field is separated by colon ( ‘:’ ) instead of comma ( ‘,’ ).
Making program Interactive and inserting multiple records in csv file.
Till now we are writing fixed records in the file. The program is not interacting with the user and
always writes two same records whenever we run it. If we want to make our program interactive
it should accept values from the user as well as it should be able to write as many records in the
file as the user wants. To accept multiple records from the user, loops can be used. For example,
The above program will accept the values till the user wants. For this purpose we have taken a
variable choice and accepted the response from the user in ‘y’ or ‘n’ form. Now on the basis of
choice the flow of the program is decided. If the user presses ‘N’ or ‘n’ the if condition becomes
True and break is encountered, which will terminate the while loop for any other value it will
again move to the beginning of the loop and accept values again.
csv.reader( ) function is used to read the csv file. It returns an iterable reader object that can be
iterated using a for loop to print the content of each row. The records are read in the form of a
list of lists. The default delimiter is comma ( ‘,’ )
For example :
Note : The file ‘e://student.csv’ must exist in the e: drive of system for successful execution of
above program.
Output :
If we have some other delimiter in place of comma we can still read that file by tweaking the
csv.reader( ) function.
For example :
Suppose we want to read a file having format shown above. In the above file the delimiter used
is colon(‘:’) not comma(‘,’). To read a file having a delimiter different from comma (‘,’) we just
have to pass an additional argument delimiter in the csv.reader( ) function.
For example :
Searching in CSV files
Example 1 : In this csv file we are going to search a particular record according to name. so, the
program of that would be look like
The above program looks like reading program except three changes that are
This statement is asking for the name of the student that we want to search in the csv file and
storing that in the name variable.
i[1] == name
In this statement we are matching name with the i[1] value. If we look carefully the student file
has three fields in the sequence Rollno, Name, Percentage.
So here name is at the position of i[1] so we are comparing i[1] with name.
else:
this else statement will execute if the break is not encountered or we can say if the loop is not
terminated prematurely.
Example 2 :
Now we want to write a program to search and display records of those students who secured
marks greater than 60.
next ( reader_obj ) : The next( ) function moves the reader_obj to the next record. We are using
this function here because the first row of the student.csv file has column names which should
not be compared with 60. Therefore next(reader_obj) will skip the header row of the student.csv
file.
int ( i [ 2 ] ) > 60 : In this statement we are converting the percentage from string to integer by
type conversion. As we all know csv file stores data in text format therefore to compare two
values we need to convert it into numbers.
flag is simply a boolean variable to keep the status of records (i.e found or not found).
Question No. 1
Neha is a student of class XII working on a project ‘student management system’ developed in
python and uses a csv file ‘student.csv’ to store data. Now Neha wants to add a new function
first_division ( ) in this project that will display the name of all those students whose percentage
is greater than 60. The format of the csv file ‘student.csv’ and the definition of first_division ( )
function are as follows.
Rollno,Name,Percentage
1,vikas,80
2,abhinav,40
3,parvez,75
4,sandeep,51
import csv
def first_division( ) :
reader_obj=csv.reader(file)
______________________ #statement2
flag=False
print ( row )
flag=True
if flag==False:
In statement 1 Neha didn’t mention the mode of the file to be opened. Identify the correct mode
in which the file will be open (if we skip the mode) from the options given below.
The program will throw an error because it is mandatory to mention the mode of the file in the
open function.
Ans : B
From the data of the student.csv file shown above it is clearly visible that the first row of the file
has the name of the columns. To find out the records having percentage more than 60 Neha has
to skip the first row because it doesn’t have any record. Identify the correct option for
statement2.
csv.next( )
csv.skip( )
next(reader_obj)
skip(reader_obj)
Ans : C
In statement3 Neha wants to compare the percentage of students with 60. Identify the suitable
option for statement 3.
row > 60
row [ 0 ] > 60
row [ 2 ] > 60
Ans : D
To keep all csv files at one place Neha moved the student.csv file from its default location to d:/
drive. What will be the effect of changing the location of student.csv file.
In open function we can only mention the name of the file, not location.
Ans : D
In this first_division( ) function Neha has not closed the file. Identify the correct statement
The program will throw an error because the file is not closed.
Ans : A
Question No. 2
Sandeep is writing a program in python to store data of employees working in ACE Infotech in
‘employee.csv’ file. While writing the program he is facing some problems. Help Sandeep to sort
out the difficulties.
def create_file( ) :
writer_obj = csv.writer(file)
writer_obj._______________ #statement 1
employee_id=input(‘Enter employee id : ‘)
record=__________________________ #statement 2
writer_obj.writerow(record)
After successfully executing the code, when sandeep opened the ‘employee.csv’ file he noted
that there are empty lines after each row. Identify the suitable options to avoid these empty
lines.
writer_obj= csv.writer(newline=’’)
writer_obj=csv.writer(file,newline=’’)
Ans : A
Before writing the actual data in the file Sandeep wants to add a row that should have the header
or column names of the field. Identify the suitable statement for blank space in statement 1
Ans : D
After executing the code successfully Sandeep noticed that every time when he runs the program
the previous data stored in the ‘employee.csv’ file disappears. How he can preserve the previous
data from disappearing.
Sandeep has to manually copy the data from ‘employee.csv’ to some other file because in python
every time we run a program to write on a file python creates a new file.
Ans : A
In statement 2 what should be the data type of variable record to write data successfully in
employee.csv file.
List
Tuple
None of them
Ans : C
Sandeep didn’t close the file. Identify the suitable option to close the file.
writer_obj.close( )
csv.close( )
file.close( )
There is no need to close the file in this case as python will automatically close the file and doesn’t
have any impact on student.csv file.
Ans : C
Question No 3
Parvez is a class XII student working on a program to read and write on student.csv file. The
format of the student.csv file is as follows. (note the fields in the file are separated by hash(‘#’) )
Rollno#Name#percentage
1#vanshika#82
2#abhishek#48
3#tanishq#58
The program is
def create_file( ) :
writer_obj.writerows(____________) #statement 3
def display_file( ) :
_________________ #statement 5
We can’t use any other separator except comma( ‘,’ ) in csv file.
Ans : A
To create a file in which values are separated by ‘#’. Identify the correct option for statement 2
csv.writer(separator=’#’, file)
csv.writer(delimiter=’#’,file)
csv.writer(file, delimiter=’#’)
Ans : D
Ans : A
Choose the suitable option to read a file having values separated by ‘#’ for blank line in statement
4
csv.reader(file)
csv.reader(file, separator=’’)
csv.reader(file, delimiter=’#’)
csv.reader(separator=’’, file )
Ans : C
Now Parvez wants to display only the names of all students from the ‘student.csv’ file. Identify
the correct option for statement 5
print (‘Name’)
Tata Technical Services is hiring students for their new project. To shortlist the candidates they
have provided the following incomplete code related to csv files and written in python to all the
candidates. On the basis of this code they have some questions for candidates
2. def create_file( ):
5. lst = [ ]
6. while True:
12. choice = input ( 'Do you have more records (y/n) : ' )
14. break
add
include
import
from
Ans : C
Write suitable code for blank space in statement 2
file =
with =
file
with
Ans : D
Ans : C
If we replace the statement 3 written in the above program by the statement given below
The statement rollno = int ( input ( ‘Enter rollno : ‘ ) ) will throw error because we can't accept
rollno as integer.
The statement record = [ rollno , name , marks ] will throw an error because we can't mix numbers
with strings in a list ( all values should be of same data type)
Ans : D
5. Identify the keyword which is used here to terminate the loop prematurely.
append
choice
True
break
Ans : D
Question No. 5
Shubham of class 12 is writing a program to create a CSV file “user.csv” which will contain user
name and password of all the users. He has written the following code. As a programmer, help
him to successfully execute the given task.
file.____________( ) #statement 3
def displayUser( ):
if row[0]== ‘man#22’ :
print ( row )
displayUser ( ) # statement 5
a) CSV
b) Csv
c) csv
Ans : C
a) r
b) w
Ans : B
a) quit( )
b) exit ( )
c) break ( )
d) close ( )
Ans : D
4. Fill the blank in statement 4 to the read the data from csv file
a) read
b) reader
c) readline
d) readlines
Ans : B
a) [ ‘manoj’, ‘man#2022’]
b) [ ‘man#2022’, ‘manoj’]
c) ‘manoj ‘, ‘man#2022’
d) Nothing
Ans : D
CONTENT DEVELOPMENT TEAM
Types of files