[go: up one dir, main page]

0% found this document useful (0 votes)
110 views42 pages

File Handling Question Bank - FIB & Case Study Questions

Uploaded by

studybiccho
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)
110 views42 pages

File Handling Question Bank - FIB & Case Study Questions

Uploaded by

studybiccho
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/ 42

ARMY PUBLIC SCHOOL KANPUR

Name of the Chapter- DATA FILE HANDLING


FILL IN THE BLANKS & CASE STUDY QUESTIONS

CBQ NO Question Content Learning Objective(if


Provided)
Q1. Ramesh is learning Python in preparation for an Application
internship exam. He is having a problem with one
question in which she has been assigned an incomplete
Python code (given below) to create a CSV file called
‘Employee.csv.’ Assist her in completing the code that
generates the CSV file with the given content.

Incomplete Code:
#Statement 1
Csvfile = open( , , newline=’’)
#Statement 2
CsvObj = csv. ( ) #Statement 3
Rows = []
Fields = [‘Empnumber’, ‘EmpName’, ‘EmpDesig’,
‘EmpSalary’]
Rows.append(Fields)
for i in range(5):
Empno = input(“Enter Employee No:”)
Name = input(“Enter Employee Name:”)
Desig = input(“Enter Designation:”)
Salary = int(input(“Enter Salary:”))
records= [ ] #Statement 4
Rows. ( ) #Statement 5
. (Rows) #Statement 6
Csvfile.close()

a. Identify the relevant module to import in the blank


space in line marked as Statement 1.
(A) import pickle (B) import txt
(C) import csv file (D) import csv
b. Identify the missing code for the blank space in line
marked as Statement 2.
(A) “Employee.txt”, ‘rb’
(B)“Employee.csv”, ’wb’
(C) “Employee.csv”, ’w’
(D)“Employee.dat”, ’w’
c. Choose the function name (with argument) that should
be used in the blank space of line marked as
Statement 3.
(A) writer(“Employee.csv”) (B) read(“Csvfile”)
(C) writer(CsvObj) (C) writer(Csvfile)
d. Identify the suitable code for blank space in line
marked as Statement 4.
(A) Empno, Name, Desig, Salary (B)
“Empno, Name, Desig, Salary”
(C) “Empno”, “Name”, “Desig”,”Salary” (D)
“Empno – Name- Desig – Salary”
e. Identify the suitable code for blank space in the line
marked as Statement 5.
(A) insert(data) (A)
delete(data)
(C) append(records) (D)
addrows(records
f. Identify the suitable code for blank space in the line
marked as Statement 6.
(A) Csvfile.load() (B)
CsvObj.dumprow()
(C) Records.reader() (D)
CsvObj.writerows()
Q2. The owners of the ‘Foodmill’ store wish to generate a Application
bill for each transaction using a binary file. In order to do
this, they have recruited a friend who is learning Python.
The friend has made a file called ‘foodmill.dat’ that
contains information like Itemno, Item Name, Qty and
Price in order to compute Total Amount, but is having
problems finishing it. Assist the friend in finishing the
code.
Incomplete Code:
import #Statement 1
File = ('foodmill.dat',' ') #Statement 2
ch='y'
while True:
Itemno = input("Enter Item No:")
Product = input("Enter Product Name:")
Qty= int(input("Enter Quantity:"))
Price = int(input("Enter Price:"))
Amount=Qty *Price
records= [Itemno,Product,Qty,Price,Amount]
pickle. #Statement 3
ch=input("Do you want to buy more. .. ")
if ch=='y' or ch=='Y':
continue
else:
break
File.close()
def Total_Amount():
f= open('foodmill.dat','rb+')
total_Amt=0
try:
while True:
R= #Statement 4
#Statement
5
print("You have purchased",R[2],R[1],"of
price","Rs",R[3],"and amount is", R[4])
: #Statement 6
f.close()
print("Total Amount is Rs",total_Amt)
a. Identify the relevant module to import in the blank
space in line marked as Statement 1.
(A) pickle (B) bin
(C) tsv (D) csv
b. Identify the code to open the file along with the access
mode so that every time the program is run, new
customer records will be added in Statement 2.
(A) open ‘rb’ (B) open ‘wb’
(C) open ‘r’ (C) write ‘w’
c. Identify the suitable code for blank space in the line
marked as Statement 3.
(A) load(records,file) (B)
dumps(record,file)
(C) dump(records,file) (C)
load(file,records)
d. Identify the suitable code for blank space in line
marked as Statement 4.
(A) pickle.load(F) (B) pickle.dump(f)
(C) pickle.load(R) (D) pickle.load(f)
e. Identify the suitable code to calculate the total Amount
in the line marked as Statement 5.
(A) total_Amt=R[4] (B)
total_Amt=R[3]+R[4]
(C) total_Amt+=R[4] (D)
total_Amt=R[4]*2
f. Identify the suitable keyword to handle the exception
(if any) that occurs during execution of the try
clause.
(A) catch (B) except
(C) stop (D) exception
Q3. A programmer has confusion in understanding the
behavior of opening a file in "w" mode. Clear his/her
confusion, by suggesting the correct option among the
given below.
The behavior of "w" mode is
A. Opening fails if the file 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, if do not exist, creates a
new file.

Q4. Rehang is assigned the task to 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+

1. Abhinav is a student of class XII, he wants to create a file


through python program which can open in excel also,
what type of file you will suggest to create.
A. Binary
B. CSV
C. Both
D. None

1. Mrs. Bhatia 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
Binary file concept.
B. She can use Python Dictionaries with Text
files.
C. She can use Python Lists without the
Binary files concept.
D. She can use Python Dictionaries without
the Binary file concept.

1. Rohit, a class 12th student, wants to write a program to


read a binary file, Which python module needs to be
imported by Rohit in his program.
A. binary
B. pickle
C. data
D. file

Q5 Ramesh wants to write into an existing file ‘story.txt’ APPLICATION,


which already had some important content in it. He has
written the code given below. Help him to complete this ANALYSIS,
code. EVALUATION AND
CREATION
fout = open('story.txt', ) # STATEMENT 1
print("Name of the file:", fout.name)
n = int(input("No. of lines to be entered:"))
l = []
for i in range(n):
fil_str = input("Enter string:")
fil_str = # STATEMENT 2
l.append(fil_str)
fout. # STATEMENT 3
# STATEMENT 4

i) Complete the code for statement 1 by writing access KNOWLEDGE AND


mode to open the file for writing. (Consider file already UNDERSTANDING
exists with some important data)
(A) a
(B) r
(C) w
(D) b
ii) Complete the code for statement 2 by adding a newline APPLICATION
character to the string entered by the user.
(A) ‘\n’
(B) fil_str+newline
(C) fil_str+’\n’
(D) fil_str+’\N’
iii) Complete the code for statement 3 by replacing the spaces APPLICATION
with the code for writing multiple strings/lines at once in
the file.
(A) writeline()
(B) writelines(l)
(C) writelines()
(D) writestrings()
iv) Replace the code for statement 4 by closing the file. KNOWLEDGE AND
(A) f.close() UNDERSTANDING
(B) close()
(C) close(f)
(D) fout.close()
Q6 Deepti wants to write into an existing file ‘story.txt’ APPLICATION,
which already has some important content in it. She has ANALYSIS,
written the code given below. Help her to complete this EVALUATION AND
code and analyze the output. CREATION

fout = # STATEMENT 1
print("Name of the file:", fout.name)
n = int(input("No. of lines to be entered:"))
for i in range(n):
fil_str = input("Enter string:")
fil_str = fil_str+"\n"
fout. # STATEMENT 2
# STATEMENT 3

i) Complete the code for statement 1 by writing code to KNOWLEDGE AND


open the file for writing. (Consider file already exists UNDERSTANDING
with some important data)
(A) open()
(B) open(story.txt,’w’)
(C) open(‘story.txt’,’a’)
(D) open(‘story.txt’)
ii) Complete the code for statement 2 by replacing the spaces APPLICATION
with the code for writing single string/line at a time in the
file.
(A) writeline()
(B) writeline(fil_str)
(C) writes(fil_str)
(D) write(fil_str)
iii) Replace the code for statement 3 by closing the file. KNOWLEDGE AND
(A) f.close() UNDERSTANDING
(B) close()
(C) close(f)
(D) fout.close()
iv) If user provides two strings as input : ANALYSIS,
String 1 : “PYTHON IS AN EASY LANGUAGE” EVALUATION AND
String 2 : “PYTHON IS POPULAR LANGUAGE” CREATION
What will be the content of the file after execution of the
code?
(A) PYTHON IS AN EASY LANGUAGE PYTHON IS
POPULAR LANGUAGE
(B) PYTHON IS AN EASY LANGUAGE
PYTHON IS POPULAR LANGUAGE
(C) PYTHON IS AN EASY LANGUAGEPYTHON IS
POPULAR LANGUAGE
(D) PYTHON IS POPULAR LANGUAGEPYTHON IS
AN EASY LANGUAGE
Q7 Consider a statement Application
fileobj = open(“myblog.txt”, ‘r’)
Which of the following options can be used to print the
last line of a text file ‘myblog.txt’?
(A) print(fileobj.readlines() -1)
(B) disp = fileobj.readlines()
print(disp[-1])
(C ) print(fileobj.readlines(-1))
(D) print(fileobj.read(-1))
Q8 Suppose the content of ‘moral.txt’ is: Application

What will be the output of the following code?


file = open(“moral.txt”)
line = file.read()
word = line.split()
for w in word:
if len(w)>8:
print(w)
file.close()
(A) Sometimes
weaknesses
discover
strengths
(B) sometimes
tested
weaknesses
strengths
(C) sometimes
weaknesses
strengths
(D) tested
show
our
but
Q9 During the practical examination of Computer Science, UNDERSTANDING
Amit has been assigned an KNOWLEDGE
incomplete search() function to search in a text file ANALYSIS
“EMP.txt”. The file “EMP.txt” is EVALUATION
created by his Teacher and the following information is
known about the file:
• File contains details of employees in text format
• File contains details of employees like Worker,
Supervisor, Manager
Amit has been assigned the task to complete the code and
print the number of the word Manager.

def search():
f = open("EMP.txt",) #Statement-1
A= #Statement-2
ct=0
for x in A:
p=x.split()
if p==”Manager”:
ct+=1
print(ct)

close() # #Statement-3
i. Name the function that can be used by Amit to read the
content of the file in statement-2.
a) f.read( )
b) f.readline ()
c) f.readlines( )
d)f.readl()
ii.Name the mode that can be used by Amit to read the
content of the file in statement-1.
a) w
b) r

c) readlines
d)readl()

iii Complete the function that can be used by Amit to


close the the file in statement-3.
a) f.read( )
b) f.close ()
c) f.readlines( )
d) f.closed ()

Q10 Sunaina wants to write a method in python to read lines UNDERSTANDING


from a text file MYNOTES.TXT and display those lines KNOWLEDGE
which start with alphabets 'K'-- ANALYSIS
def display (): EVALUATION
file=open(MYNOTES.TXT’ , ) #
statement-1
lines=file. () # statement-2
while line:
if line[0]==’K’ :
print(line)
line=file. () # statement-3
file.close()
i.Name the mode that can be used by Amit to read the
content of the file in statement-1.
a) w
b) r
c) readlines
d)readl()

ii Name the function that can be used by Sunaina to read


the content of the file in statement-2.
a) f.read( )
b) f.readline ()
c) f.readlines( )
d)f.readl()
iii Name the function that can be used by Sunaina to read
the content of the file in statement-3.
a) f.read( )
b) f.readline ()
c) f.readlines( )
d)f.readl()

Q11
(CASE STUDY: 1)

f=open("data.txt",'w')
f.write("Hello")
f.write("Welcome to my Blog")
f.close()
f=open("data.txt",'r')
d=f.read(5)
print(d) # First Print Statement
f.seek(10) Knowledge
d=f.read(3) Understanding
print(d) # Second Print Statement Analysis
f.seek(13) Application
d=f.read(5)
print(d) # Third Print Statement
d=f.tell()
print(d) # Fourth Print Statement
1 Refer to the above code (CASE STUDY:1) Write the
output of the First Print statements :
a. Hello
b. Hell
c. ello
d. None of the above
2 Refer to the above code (CASE STUDY:1) : Write the
output of Second Print Statement
a. om
b. me
c. co
d. None of the above
3 Refer to the above code (CASE STUDY:1) : Write the
output of Third Print Statement
a. e to m
b. e to my
c. to my
d. None of the above
4 Refer to the above code (CASE STUDY:1) : Write the
output of Fourth Print Statement

a. 17
b. 16
c. 19
d. 18

Q12 CASE STUDY : 2

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. Knowledge
Understanding
def FilterWords(): Analysis
c=0 Application
file=open('NewsLetter.TXT', ' ') #Statement-1
data = file. #Statement-2
line = #Statement-3

linecount= : #Statement-4
print(“No of lines”,linecount)
#Statement-5
FilterWords()
1 Fill in the statement 1 with appropriate access mode
a) rb

b) r

c) w

d) a

2 Fill the statement 2 with appropriate function to read 5


characters
a) read()

b) read(5)

c) readline(5)

d) get(5)

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

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


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

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


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

Q13. Suppose the content of "Myfile.txt" is Knowledge ,


Humpty Dumpty sat on a wall Understanding &
Humpty Dumpty had a great fall Application
All the king's horses and all the king's men
Couldn't put Humpty together again
Rohit, a student of class 12, is learning Python. During the
examination he has been given a stub Python program
(shown below) to count no of independent words has started
from vowels. Help him in completing the code.

myfile = open("Myfile.txt", ) # Statement 1


vlist = list("aeiouAEIOU")
vc=0
s = myfile.read()
w= # Statement 2
for y in : # Statement 3
if in : #Statement 4
vc+=1
print(vc)
myfile. # statement 5

(i) Identify the suitable code for blank space in the line
marked as Statement-1.
A. ‘w’
B. ‘w+’
C. ‘rb’
D. ‘r+’
(ii) Identify the suitable code for blank space in the line
marked as Statement-2.
A. Vlist.split()
B. S.split(‘*’)
C. s.split()
D. S.split()
(iii) Identify the suitable code for blank space in the line
marked as Statement-3.
A. vlist
B. s
C. w
D. myfile
(iv) Identify the suitable code for blank space in the line
marked as Statement-4.
A. y & w
B. y[0] & s
C. y & s
D. y[0] & w
(v) Identify the suitable code for blank space in the line
marked as Statement-5.
A. Off()
B. Close()
C. close()
D. open()
Q14. Consider the content of ‘rhyme.txt’ file:
Amit, a student of class 12 Science, is learning Python. During
the examination he has been given a stub Python program
(shown below) to count no of lines in ‘rhyme.txt’ file starts
with H or T has started from vowels. Help him in completing
the code.

fileobj= (‘rhyme.txt', ) #
Statement 1
count = 0
L=fileobj. #
Statement 2
for i in L:
if ( =='H' or ==’T’ ): #
Statement 3

count= #
Statement 4
print(count) #
Statement 5
fileobj.close()

(i) Identify the suitable code for blank space in the line
marked as Statement-1.
A. Open () & ‘w’
B. open() & ‘w+’
C. open() & ‘r’
D. Open() & ‘r+’
(ii) Identify the suitable code for blank space in the line
marked as Statement-2.
A. read()
B. readlines()
C. readline()
D. readlines(5)
(iii) Identify the suitable code for blank space in the line
marked as Statement-3.
A. L[0]
B. i[0]
C. i
D. L[i]
(iv) Identify the suitable code for blank space in the line
marked as Statement-4.
A. 1
B. count+2
C. count+count
D. count+1
(v) Identify the ouput that will be display by Statement-5.
A. 1
B. 2
C. 3
D. 4
Q15 A Text file ‘data.txt’ content following lines. A Python Learning Objective
code is given to read the content of the file. Read the code
given below carefully and answer the following
questions.
File Content
Hello
Welcome to my blog
One of the best blog for Python

Code:
f=open("data.txt",'r')
d=f.read(5)
print(d) # Statement 1
f.seek(10)
d=f.read(3)
print(d) # Statement 2
f.seek(13)
d=f.read(5)
print(d) # Statement 3
d=f.tell()
print(d) # Statement 4
f.close()
f.read() ## Statement 5
1 What is output of statement 1 Application
(A) Hello
(B) ello
(C) hello
(D) Hello W
2 What is output of statement 2 Application
(A) com
(B) lco
(C) eco
(D) None of the above
3 What is output of statement 3 Application
(A) e to
(B) to my
(C) o my b
(D) Error
4 What is output of statement 4 Creation
(A) 18
(B) 19
(C) 17
(D) 16
5 What is out of statement 5 Analysis
(A) my blog
One of the best blog for Python
(B) One of the best blog for Python
(C) Error
(D) None of the Above
Q16. A Text file ‘myfav.txt’ content following lines. Python
code is given to count the number of word ‘this’ present
in the file. Read the code given below and answer the
following questions.
File Content:
This is India, this is great country. this is the place where
great personalities were born. this is the nation harmony.

Code:
file=open('myfav.txt','r')
count = 0
l=file. () #statement 1
word= l. () #statement 2
for i in word:
if(i==' '): #statement 3
count=count+ #statement 4
print(count) # statement 5
file.close()
1 Write the correct function name that reads entire content Creation
as string (statement 1).
(A) Read
(B) read
(C) readline
(D) Readlines
2 Write the correct function name that breaks the string into Creation
list of words (statement 1).
(A) split()
(B) break()
(C) split(‘space’)
(D) break(‘space’)
3 File the blank that correct count the desired word in the Application
file (statement 3).
(A) This
(B) ‘This’
(C) ‘this’
(D) this
4 What is the literal value to increase the value of count by Analysis
1 statement 4
(A) 1
(B) 2
(C) 3
(D) 4
5 What is the output of statement 5 Analysis
(A) 5
(B) 2
(C) 3
(D) 4
Q17. Amit has written the following code in Python. Application
f=open("empfile.dat","ab") # Statement 1
print(f.closed) # Statement 2
f.close() # Statement 3
print(f.closed) # Statement 4
Answer the following questions based on the above
program
i.)In which mode the file will be opened.
(A) read binary
(B) write binary
(C) append binary
(D) None of the above
ii.)What will be the output of statement 2?
(A) False
(B) True
(C) 0
(D) 1
iii.)What will be the output of statement 4?
(A) False
(B) True
(C) 0
(D) 1
iv.)What is f in statement 1?
(A) List
(B) Dictionary
(C) File object
(D) Tuple
v.)Can we perform any task on the file ‘empfile.dat’
through the file object ‘f’ after statement 3?
(A) YES
(B) NO
(C) Can't say
(D) None of the above
Q18. Ravi has written the following code in Python. Application
fb=open("stu.dat","wb+") # Statement 1
print(fb.closed) # Statement 2
fb.close() # Statement 3
print(fb.closed) # Statement 4
Answer the following questions based on the above
program
i.)In which mode the file will be opened.
(A) read binary
(B) write and read binary
(C) append binary
(D) None of the above
ii.)Which operation is possible after statement 1?
(A) write
(B) read
(C) append
(D) write and read
iii.)What will happen if the file “stu.dat” is unavailable?
(A) File is created with ‘wb+’ mode
(B) File will be created in append mode
(C) File will be created in write only mode
(D) Error
iv.)What is fb in statement 1?
(A) Variable
(B) String
(C) List
(D) File object
Q19. Given a binary file “emp.dat” has structure (Emp_id, Application
Emp_name, Emp_Salary). Write a function in Python
countsal() in Python that would read contents of the file
“emp.dat” and display the details of those employee
whose salary is greater than 20000.
import pickle
def : Line1
f = open (“emp.dat”, “ ”) Line 2
n=0
try:
while True:
rec = Line 3
if rec[2] > 20000:
print(rec[0], rec[1], rec[2], sep=”\t”)
num = num + Line 4
except:
f.close() Line 5

Q1. In the above program, choose correct option for Line


1.
(A) countsal() (B) CountSal() (C) Sal()
(D) Count()

Q2. In the above program, choose correct option for Line


2.
(A) ab (B) rb (C) wb
(D) None

Q3. In the above program, choose correct option for Line


3.
(A) Pickle.dump() (B) pickle.read()

(C) pikle.load() (D) None of these


Q4. In the above program, choose correct option for Line
4.
(A) -1 (B) 1 (C) 2
(D) 0

Q5. In the above program, choose correct option for Line


5.
(A) f.close() (B) f.exit() (C) f.stop()
(D) None
Q20. Mr. Zack has given the following code to modify the Application
records of employees from employee.dat used in above Knowledge
code. He has to increase Rs. 2000 in the salary of those
who are getting less than 15000. Mr. Zack has to find the
records and change the salary in place. His teacher gave
him partial code. Help him to complete the code.

import pickle as pk
found=False
emp={}
fin = #1 statement : open file both in read
write mode
# read from file
try:
while true:
pos= #2 store file pointer position before
reading record
emp= #3 to read the record in emp
dictionary
if emp[‘salary’]<15000:
emp[‘salary’]+=10000
#4 place file pointer at exact
location of record
pickle.dump(emp,fin)
found=True
except EOFError:
if found==False:
print(“record not found”)
else:
print(“successfully updated”)
fin.close()
Q1. In #1 statement open the file in read and write mode.
Which statement is used out of the followings?
a) open(“employee.dat”,’rb+’)
b) open(“employee.dat”,’r+’)
c) open(“employee.dat”,’a’)
d) open(“employee.dat”,’rb’)
Q2. Choose the appropriate statement to complete #2
statement to store file pointer position before reading
record.
a) pk.seek(pos)
b) fin.tell()
c) pk.position()
d) pk.tell()
Q3. Choose the appropriate statement to complete #3
statement to read record in emp dictionary.
a) pk.read(fin)
b) pickle.load(fin,emp)
c) pk.dump(emp)
d) pk.load(fin)
Q4. Choose the appropriate statement to complete #4
statement to place file pointer at exact location of record.
a) fin.seek(pos)
b) pos=fin.seek()
c) fin.position()
d) none of the above
Q21 Given a binary file “emp.dat” has structure (Emp_id, Application
Emp_name, Emp_Salary). Write a function in Python
countsal() in Python that would read contents of the file
“emp.dat” and display the details of those employee
whose salary is greater than 20000.
import pickle
def : Line1
f = open (“emp.dat”, “_ ”) Line 2
n=0
try:
while True:
rec = Line 3
if rec[2] > 20000:
print(rec[0], rec[1], rec[2], sep=”\t”)
num = num + Line 4
except:
f. Line 5

1. In above program , choose correct option for Line 1


A) countsal()
B) Countsal()
C) Sal()
D) Count()
2. In above program , choose correct option for Line 2
A) ab
B) rb
C) wb
D) None of the above

3. In above program , choose correct option for Line 3


A) pickle.dump()
B) pickle.read()
C) pickle.load()
D) None of the above

4. In above program , choose correct option for Line 4


A) -1
B) 2
C) 0
D) 1
Q22 A binary file “emp.dat” has structure [empid, empname, Application
empsalary]. 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() #line4

1. To open the file for reading the data in line marked as


line-1.
A) fobj=open("emp.dat","rb")
B) fobj=open("emp.dat","r")
C) obj=open("emp.dat","r+")
D) fobj=open("data.dat","rb")

2. The module used in line2


A) PICKLE
B) pickling
C) pickle
D) None of these

3. Identify the salary to be checked in the code marked as


line-3.
A) 50000
B) 20000
C) 24000
D) 10000

4. Which of the following File Modes creates a new


binary file, if the file does not exist? (choose one/more)
A) ‘r’
B) ‘wb’
C) ‘w’
D) ‘a’

Q23. Read the program code given below and answer the Learning Objective:
following questions……..
((
Examine the code
Consider the following program to enter the following example to solve an
records as per below format in a binary file: application oriented
Item No integer problem and propose the
solution
Item_Name string
Qty integer
Price float
Number of records to be entered should be accepted from
the user. Read the file to display the records in the
following format:
Item No:
Item Name:
Quantity:
Price per item:
Amount: (to be calculated as Price * Qty)
))

import pickle
def input_record():
rec={}
rec['Item No']=int(input('Enter Item No'))
rec['Item_Name']=input('Enter Item Name')
rec['Qty']=int(input('Enter Quantity'))
rec['Price']=float(input('Enter Price'))
return rec

def create_file():
fileobject=open('data.dat','wb')
n=int(input('Enter Number of records to be entered'))
for i in range(n):
record=input_record()
pickle.dump(record,fileobject)
if i+1 < n:
print('Next Record')
print(n,'Records entered')

def show_records():
fileobject=open('data.dat',' ') #statement1
i=1
while True: #statement2
try:
record=pickle. #statement2
print('Record:',i)
print('Item No:',record['Item No'])
print('Item Name:',record['Item_Name'])
print('Quantity:',record['Qty'])
print('Price per item:',record['Price'])
print('Amount:', record['Qty'] * record['Price'])

i += 1
except:
pass

1 Fill in the blanks for statement1 , so that records can be


retrieved in memory.
(A) ab
(B). wb
(C). rb
(D) wb+

2 Fill in the blanks for statement2 , so that record can be


fetched from file.
(A) dump(record, fileobject)
(B) load( fileobject)
(C) dump( fileobject)
(D) load( record, fileobject)

Q24. Ajay want to read data from binary file “file.dat” help Understanding,
him to complete program. Knowledge,
import pickle Application, Evaluation
std = { }
fin = open(“file.dat”, ‘ ’) # (Statement1)
try:
while : # (Statement 2)
std = (fin) # (Statement3)
print(std)
: # (Statement 4)
fin. () # ( Statement 5)

Help Ajay to complete the code as per the following


instructions.

a) Complete Statement1 to open binary file in read


mode.
b) Complete Statement 2 to place a condition till file
not reach at the end of file
c) Complete Statement 3 to read a record std
dictionary from fin
d) Complete Statement 4 it execute if error occurred
in try statement
e) Complete Statement 5 to Close file

Q25. Raj has been given following incomplete code, which Understanding,
takes a Employee’s details (Ecode, Ename, and Salary) Knowledge,
and writes into a binary file emp.dat using pickling. Application, Evaluation
import pickle
eno = int((input(“enter emp. Code”))
ename = input(“Enter emp. Name”)
sal = int(input(“Enter Emp. Salary”))
emp1 = {“Ecode”:eno, “Ename”:ename, “Salary”:sal}
with as fh: # Statement 1
# Statement 2
as fin # Statement 3
# Statement 4
print(Remp)
if Remp[“Salary”] > = 85000:
print(“Eligible for increment”)
: # Statement 5
print(“Not eligible for increment”)

Help Raj to complete the code as per the following


instructions.
a) Complete Statement1 so that the mentioned binary
file is opened for writing in fh object using a with
statement.
b) Complete Statement2 so that the dictionary
emp1’s contents are written on the file opened in
step (a)
c) Complete Statement3 so that the earlier created
binary file is opened for reading in a file object
namely fin, using a with statement.
d) Complete Statement4 so that the contents of open
file in fin are read into a dictionary namely Remp.
e) Complete Statement5 so that if condition false
“Not eligible for increment” message display.
Q26. Seema want to read data from a text file. She faced some Understanding
problems while executing the given code. Based on this
code find out the answers of the following questions.
def b_read( ):
import # Line1
f = open("data.dat" , ) # Line 2
d= # Line 3
print(d)
# Line
4
i) Which module Seema will use for binary file handling. Analysis
a) math
b) pickle
c) random
d) No need to import any module
ii) Write the correct code for line 2. Analysis
a) “r”
b) “rb”
c) “r+”
d) “wb”
iii) What code Seema should write to read data from file in Evaluation
line 3.
a) f.read()
b) f.readlines()
c) f.load(f)
d) None of the above
iv) Write to code in line 4 to access the function. Creation
a) b_read()
b) print(b_read())
c) call b_read()
d) No need to call any function
Q27. Amit has been assigned an incomplete search() function Understanding
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.
• File contains details of students in [roll_no, name
,marks] format.
• File contains details of 10 students (i.e. from roll_no 1
to 10) and separate list of each student is written in the
binary file using dump().
Amit has been assigned the task to complete the code and
print details of roll number 5.
def search():
f = open("student.dat", )
#Statement-1
:
#Statement-2
while True:
rec = pickle.
#Statement-3
if( ):
#Statement-4
print(rec)
except:
pass

#Statement-5
i) In which mode Amit should open the file in Statement-1? Analysis
a) r
b) r+
c) rb
d) wb
ii) Identify the suitable code to be used at blank space in line Creation
marked as Statement 2
a) if(rec[0]==1)
b) for i in range(10)
c) try
d) d) pass
iii) Identify the function (with argument), to be used at blank Evaluation
space in line marked as Statement-3.
a) load()
b) load(student.dat)
c) load(f)
a) d) load(fin)
iv) What will be the suitable code for blank space in line Creation
marked as Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
a) d) rec[0]==5
v) Which statement Amit should use at blank space in line Evaluation
marked as Statement-5 to close the file.
a) file.close()
b) close(file)
c) f.close()
a) d) close()
Q28. Mohak is collecting data of persons of a locality.He is
storing/retrieving data from a file LOCALITY.CSV. It
consists some records (sno, name, location). He has
written the following code in python. As a programmer,
you have to help him to successfully execute the program.

import # Line 1
def addRecord(Lst) # Line 2
f=open(“LOCALITY.CSV”, ) # Line 3
obj=csv.writer(f)
obj.writerow(Lst)
# Line 4

def ShowRecord():
with open(“LOCALITY.CSV”, ”r”) as file:
obj=csv. (file) # Line 5
for rec in obj:
print(rec[0], “#”, rec[2])

C_1=[1,’XYZ’, ‘Guwahati’]
C_2=[2,’PQRYZ’, ‘Dibrugarh’]
addRecord(C_1)
addRecord(C_2)
ShowRecord()
Understanding
1. Which module should be imported in Line 1?
(A) pickle
(B) csv
(C)file
(D) text
Creation
2. Which symbol is missing in Line 2?
(A) ::
(B) ,
(C) @
(D) :
Understanding
3. Which statement will be written at Line 4?
(A) f.close
(B) obj.close()
(C) f.close()
(D) obj.close
Application
4. Which function to be used in Line 5 to read the data
from a csv file.
(A) read()
(B) readline()
(C) readlines()
(D) reader()
Q29. Amayra has a branch1.csv file which has the name, class
and section of students. She receives a branch2.csv which
has similar details of students in second branch. She is
asked to add the details of branch2,csv into branch1.csv.
As a programmer, help her to successfully execute the
given task.
csv #Statement1
file = open('branch1.csv', b , newline="");
writer = csv. (file) #Statement2
with open('branch2.csv','r') as csvfile #Statement3
data = csv.reader(csvfile)
for row in data:
writer.writerow( )#Statement4
file. ()#Statement5
Understanding
1. Which statement is to be used in place of blank space
of Statement 1?
(A) include
(B) import
(C) create space Creation
(D) includes

2. Which symbol is missing in Statement 3?


(A) ::
(B) ,
(C) @ Understanding
(D) :

3. Which statement will be written at Statement 5?


(A) f.close
(B) obj.close()
(C) f.close() Application
(D) obj.close

4. Fill in blank space in Statement 5 to write the data to a


csv file.
(A) write
(B) data
(C) row
(D) writeline
Q30. Rajeev sir, class teacher of class XI is writing a program APPLICATION
to create a Comma Separated file “Studrecord.dat” which
will contain roll no., name of student and total marks
obtained by the students of his class. 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=
'')
s=csv. (f)
#Line 2
s.writerow(['RollNo','Name','Mark
s'])
rec=[]
while True:

print("ENTER STUDENT DETAILS:


")
r=int(input("ENTER ROLL NO.:
"))
n=input("ENTER NAME: ")
m=int(input("ENTER MARKS: "))
stu=[r,n,m]
rec. (stu)
#Line 3
ch=input("DO YOU WANT TO
CONTINUE (Y/N): ")
if ch=='n' or ch=='N':
break

for i in rec:
s. (i)
#Line 4
f.close()

i) Identify the suitable code for blank space in the line


marked as Line 1.
a) csv file
b) CSV
c) csv
d) cvs

ii) Choose the function name that should be used in the


blank space of the line marked as Line 2.
a) writer
b) write
c) writeline
d) writelines

iii) Write the method through which data can be added in


the list rec in line 3.
a) insert
b) add
c) append
d) into

iv) Write the function in line 4 by using which we will be


able to store records present in the list rec into the file
student.csv, one record at a time.
a) writerows
b) writelist
c) write
d) writerow

Q31 Prakash is making a software on “Countries and their APPLICATION


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

import csv
# Function to add a new record in CSV
file
def (Country,Currency):
# Statement-1
f=open("CURRENCY.CSV"," ")
# Statement-2
fwriter=csv.writer(f)
fwriter.writerow([ ])
# Statement-3
f.close()
# Function to display all records from
CSV file
def ShowRec():
with open("CURRENCY.CSV","r") as
NF:
NewReader=csv. (NF)
# Statement-4
for rec in NewReader:
if len(rec)!=0:
print(rec[0],rec[1])
AddNewRec("INDIA","RUPEE")
AddNewRec("JAPAN","YEN")

i) Choose the Name of the function in Statement-1.


(A) AddNewRec
(B) Addnew
(C) Addrec
(D) AddNewRec()

ii) Choose the file mode to be passed to add new records


in Statement-2.
(A) w
(B) r
(C) w+
(D) a

iii) Identify the correct variables in Statement-3 to store


data to the file.
(A) country,currency
(B) Country,Currency
(C) Coun,Cur
(D) [Country,Currency]

iv) Choose the correct option for Statement-4 to read the


data from a csv file.
(A) Reader()
(B) reader()
(C) read
(D) reader

ANSWER

CBQ NO Answer
1.a. (D) import csv
1.b (C) “Employee.csv”, ’w’
1.c (D) writer(Csvfile)
1.d (A) Empno, Name, Desig, Salary
1.e (C) append(records)
1.f (D) CsvObj.writerows()
2.a (A) pickle 51
2.b (B) open ‘wb’
2.c (C) dump(records,file)
2.d (D) pickle.load(f)
2.e (C) total_Amt+=R[4]
2.f (B) except
3 1. D
3 2. C
3 3. B
3 4. A
3 5. B
4 i) (A) a
ii) (C) fil_str+’\n’
iii) (B) writelines(l)
iv) (D) fout.close()
5 i) (C) open(‘story.txt’,’a’)
ii) (D) write(fil_str)
iii) (D) fout.close()
iv) (B) PYTHON IS AN EASY LANGUAGE
PYTHON IS POPULAR LANGUAGE
6. B

7. A
8. i C ii B iii B
9. i B ii C iii B

10 1. b) r

10 2. b) read(5)

10 3. b) file.readlines()

10 4. b) len(line)
10 5. a) file.close()

11. Answer
(i) D
(ii) C
(iii) C
(iv) D
(v) C
12. Answer
(i) C
(ii) B
(iii) B
(iv) D
(v) D
13. 1 A
13. 2 A
13. 3 A
13. 4 A
13. 5 C
14. 1 B
14. 2 A
14. 3 D
14. 4 A
14. 5 C
15

(i.) A

(ii.) A

(iii.) B

(iv.) C

(v.) B

16.
(i.) B

(ii.) D
(iii.) A

(iv.) D

17. Q1. (A) countsal()


Q2. (B) rb
Q3. (C) pikle.load()
Q4. (B) 1
Q5. (A) f.close()
18. Q1. a) open(“employee.dat”,’rb+’)
Q2. b) fin.tell()
Q3. d) pk.load(fin)
Q4. b) pos=fin.seek()
19.
1 A
2 B
3 C
4 D
20.
1 A
2 C
3 B
4 B
21. C

22. B

23. a) fin = open(“file.dat”, ‘rb ’)


a) while True:
a) std = pickle.load(fin)
a) except :
a) fin.close()
24. a) with open(“emp.dat”, “wb”) as fh:
a) pickle.dump(emp1, fh)
a) with open(“emp.dat”, “rb”) as fin:
a) Remp = pickle.load(fin)
a) else:
25.
i B
ii B
iii C
iv A
26.
i C
ii C
iii C
iv A
v C
27. 1.(B)
2.(D)
3.(C)
4.(D)
28. 1.(B)
2.(D)
3.(C)
4.(C)
29. i)
ii)
iii)
iv)
30. i)
ii)
iii)
iv)

Made by: Kumar Gaurav

You might also like