Binary files in Python
Topic Covered
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
MCQ on Binary File in Python
SECTION – A
Which of the following statement opens a binary file record.bin in write mode and writes data from a list lst1 = [1,2,3,4] on the binary file?
with open(‘record.bin’,’wb’) as myfile:
pickle.dump(lst1,myfile)
with open(‘record.bin’,’wb’) as myfile:
pickle.dump(myfile,lst1)
with open(‘record.bin’,’wb+’) as myfile:
pickle.dump(myfile,lst1)
with open(‘record.bin’,’ab’) as myfile:
pickle.dump(myfile,lst1)
Which module is required to use built in function dump()
(a) Math (b)flush (c)pickle (d)csv
3.Which of the following function is used to write data in binary mode?
(a)write (b)output (c)dump (d)send
4.To read 2 characters from file object f1 command should be
(a)f1.read(2) (b)f1.read() (c)f1.readline() (d) f1.readlines()
5.To get byte position from the beginning of file, function used is –
(a)seek (b)tell (c)read (d)write
6.The file pointer, used to go to particular position
(a)seek (b)tell (c)read (d)write
7.If a file is opened for reading, which of the following statements is not true?
- The file must exist on the disk on the specified path
- If the file exists at the specified path, the file is successfully opened.
- The file even if at a different location on disk other than the specified path, will get open
- Python gives error if the file does not exist at the specified path
Answer : c) The file even if at a different location on disk other than the specified path, will get opened.
8.To read 24 characters from a file object infi, we use
- Infi.read() b. infi.read(24)
- Infi.readline() d. infi.readlines
Answer: b) infi.read(24)
9.The readlines() method returns__________
- a str b. a list of integers
- a lit of single characters d. a list of lines
Answer : d) a list of lines.
10.Which of the following is not a valid mode to open a file.
- ab b. rw
- wb d.w+
Answer : b) rw
11.Which of the following functions do you use to write data in the binary format?
- Write() b. output()
- dump() d. send()
Answer : c) dump().
12.Which of the following commands can be used to read the entire contents of a file
as a string using the file object <tmpfile>?
- tmpfile.read(n)
- tmpfile.read()
- tmpfile.readline()
- tmpfile.readlines()
Answer : b. tmpfile.read()
13.Which of the following command is used to open a file “c:\temp.txt” for writing in binary format only?
- outfile = open(“c:\temp.txt”, “w”)
- outfile = open(“c:\\temp.txt”, “wb”)
- outfile = open(“c:\temp.txt”, “w+”)
- outfile = open(“c:\\temp.txt”, “wb+”)
Answer : b. outfile = open(“c:\\temp.txt”, “wb”)
14._____________ is the process of converting Python object hierarchy into a byte stream so that it can be written into a file.
- a) Pickling
- b) Unpickling
- c) Dumping
- d) Loading
Answer: a
15._______ is the process of reading from a binary file
- a) Pickling
- b) Unpickling
- c) Dumping
- d) Loading
Answer: b
16.___________ of pickle module will unpickle the data coming from the binary file.
a) load()
b) dump()
c) writer()
d) insert()
Answer : a
17.___________ of pickle module will pickle the data in the binary file.
a) load()
b) dump()
c) writer()
d) insert()
Answer : b
18._______________ will return the current position of file pointer in the file
- a) seek()
- b) search()
- c) tell()
- d) print()
Answer : c
19.________ places the file pointer at the specified position in the open file.
- a) seek()
- b) search()
- c) tell()
- d) print()
Answer : a
20.F.seek(20,0) will move the file pointer 20 bytes in forward direction from
beginning of file. State True or False
- a) True
- b) False
Answer : a
21.F1.seek(-5,1) will move the file pointer 5 bytes backwards from end of file.
State True or False
- a) True
- b) False
Answer : b
22.Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is the default value of reference_point?
- a) 0
- b) 1
- c) 2
- d) 3
Answer : a
- Which of the following statements is true?
a) pickling creates an object from a sequence of bytes
b) pickling is used for object serialization
c) pickling is used for object deserialization
d) pickling is used to manage all types of files in Python
Answer : b
- “wb” mode in file handling also can be written as
(a) w*b (b) w/b (c) w+b (d) none of these
- What is unpickling?
(a) It is used for object serialization (b) It is used for object deserialization
(c) None of the mentioned (d) All of the mentioned
- What is the extension of binary file
(a).dat (b).txt (c).bin (d).file
- Identify the invalid mode from the following.
(a) a (b) r+ (c) ar+ (d) w
28.Which value will be shown if you try to open a binary file using a text
(a) Default value (b) Advance Value
(c) Garbage value (d) Parameter Value
29.Binary file is stored in terms of
(a) bit (b) bytes (c) nibble (d) mnemonics
30.Mode used for reading from pickle file is
(a) rb (b) r (c) br (d) read
- When file is opened as “with open” then file __________ automatically.
(a) reads (b) writes (c) closes (d) opens
32.Which of the following commands is used to open the file “STUDENT.DAT” for writing only in binary format?
(a) F= open(“STUDENT.DAT”,’wb’)
(b) F= open(“STUDENT.DAT”,’w’)
(c) F= open(“STUDENT.DAT”,’wb+’)
(d) F= open(“STUDENT.DAT”,’w+’)
- Which of the following commands is used to write the list L into the binary file, STUDENT.DAT?
(a) pickle.write(L,f)
(b) pickle.write(f, L)
(c) pickle.dump(L,F)
(d) f=pickle.dump(L)
34.Which of the following commands is used to read each record from the binary file STUDENT.DAT?
(a) R = pickle.load(F)
(b) pickle.read(r,f)
(c) r= pickle.read(f)
(d) pickle.load(r,f)
35.Which of the following file mode opens a file for append or read a binary file and moves the files pointer at the end of the file if the file already exist otherwise create a new file?
(a) a (b) ab (c) ab+ d) a+
36.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.
37.The syntax for dump () method
- dump(data_object, file_object)
- dump[data_object, file_object]
- dump[file_object]
- dump[data_object]
- Binary files represent the actual content
(a)image (b) audio (c) video (d) All of these
39.The process by which a pythonobject is converted to a byte stream is called as
(a)Unpicking (b) loading (c) pickling (d) Dumping
40.Which of the following statements correctly explain the function of seek() method?
(a) tells the current position within the file.
(b) determines if you can move the file position or not.
(c) indicates that the next read or write occurs from that position in a file.
(d) moves the current file position to a given specified position
41.What is ‘f’ in the following statement?
f=open(“Data.txt” , “r”)
(a) File Name (b) File Handle (c)Mode of file(d)File Handling
MCQ on Binary File in Python
SECTION – B
- The following code has some errors. Identify the error line(s)
import pickle
f = open (‘example.dat’, rb)
f.dump([2,3,4])
f.close()
(a) Line 1 and 2 have the errors
(b) Lines 3 and 4 have errors
(c) Line 2 and 3 have the errors
(d) Lines 2 has error
- Rahul is trying to read data from a binary file test.bin and store it into
List L. Consider the following code written by him.
import pickle as p
with open(‘test’,’rb’) as f:
_________________ #statement 1
Identify the missing code in Statement 1.
(a) f=p.load(L) (b) p=p.load(L) (c) L=p.load(f) (d) f=L.load(p)
- What is the output produced by the following code:
import pickle
score =[10,20,30,40,50,60]
with open(‘test.dat’,’wb’) as fout:
for ix in score:
pickle.dump(ix,fout)
size=0
with open(‘test.dat’,’rb’) as fin:
num=pickle.load(fin)
size+=num
num=pickle.load(fin)
print(size,end=’,’)
num=pickle.load(fin)
size+=num
print(size)
(a)10, 50 (b) 10, 40 (c). 20, 50 (d). 10, 60
- What will be displayed by the following code?
import pickle
colors=[‘red’,’green’,’blue’,’grey’,’pink’]
fout =open(‘test.dat’,’wb’)
pickle.dump(colors,fout)
with open(‘test.dat’,’rb’) as fin:
lst=pickle.load(fin)
print(lst[1:5:2])
(a) [‘green’, ‘blue’] (b)[‘red’, ‘blue’] (c) [‘green’, ‘grey’] (d) [‘red’, ‘green’]
- The binary file STOCK.DAT is containing following fields SName and Price
Function Billing() is created in Python to read each record of a pickled file
STOCK.DAT, and display the Total Price of all the records in the file.
import pickle
def Billing():
file=open(‘STOCK.DAT’,’rb’)
IRec=pickle.load(file) #To read the object from file
Totprice=0
for I in IRec:
print (Totprice)
file.close()
Choose appropriate statement to calculate the total price from the following:
(a) Totprice=I[1] (b) Totprice=+I[1]
(c) Totprice+=I[1] (d) Totprice=I+Totprice
- When function SPLDOCS() is executed, it display all the content from a
pickled file DOCS.DAT, where Specialisation of DOCTORS is
“CARDIOLOGY”.
def Disp(s):
print (s.Name,”#”,s.Specialisation)
def SPLDOCS():
D=DOCTORS()
file=open(‘DOCS.DAT’,’rb’)
try:
while True:
D=pickle.load(file)
if D.Specialisation == ‘CARDIOLOGY’:
________
except EOFError:
pass
file.close()
To fill the missing statement 1, choose the statement to call function Disp
(a) D[Disp()] (b) D.Disp() (c) Disp(D) (d) Disp[D]
- Sunil is writing a program to search for the details a particular student.
He has got difficulties in completing the code. Help him to
complete it.
______ open(‘student’,rb) as ______:
Complete the open() statement
124
124
(a) filehandle, filename (b). filename, filehandle
(c) with, filehandle (d) with,filename
- Aman wants to read pickled file ELECTION.DAT and displays
every such Name whose Count is less than 10 but facing some problems
to give the condition.
The File contains the following fields :Name,Count
import pickle
def cLowCount():
file=open(‘ELECTION.DAT’,’rb’)
ERec=pickle.load(file) #To read the object from file
for E in ERec:
if __________: # statement 1
print (E[0] )
file.close()
Choose the correct option which satisfied the condition.
(a) E<10 (b) E[2]<10 (c) E[1]<10 (d) E[0]<10
- Observe the below code and write which of the following is
converting the list into bytes is
list1 = [23, 43, 55, 10, 90]
newFile = open(“binaryFile”, “wb”)
newFile.write(bytearray(list1))
newFile.close()
(a) byte array() (b) newFile (c) write (d) wb
125
125
- Raghav is trying to write an object obj1 = (1,2,3,4,5) on a
binary file “test.bin”. Consider the following code written by him.
import pickle
obj1 = (1,2,3,4,5)
myfile = open(“test.bin”,’wb’)
pickle. #Statement 1
myfile.close()
Identify the missing code in Statement 1.
(a) dump(myfile,obj1)
(b) dump(obj1, myfile)
(c) write(obj1,myfile)
(d) load(myfile,obj1)
- . Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin.
Consider the
following code written by him.
import pickle
tup1 = (1,2,3,4,5)
myfile = open(“test.bin”,’wb’)
pickle._______ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
126
126
- dump(myfile,tup1)
- dump(tup1, myfile)
- write(tup1,myfile)
- load(myfile,tup1)