File Handling Question Bank - FIB & Case Study Questions
File Handling Question Bank - FIB & Case Study Questions
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. w
B. r+
C. r
D. w+
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
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()
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
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
b) read(5)
c) readline(5)
d) get(5)
b) file.readlines()
c) file.readline()
d) readlines()
(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
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
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
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)
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”)
#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
import
#Line 1
f=open("student.csv","w",newline=
'')
s=csv. (f)
#Line 2
s.writerow(['RollNo','Name','Mark
s'])
rec=[]
while True:
for i in rec:
s. (i)
#Line 4
f.close()
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")
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
22. B