CBSE CS

cbse cs logo

Home

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?

  1. The file must exist on the disk on the specified path
  2. If the file exists at the specified path, the file is successfully opened.
  3. The file even if at a different location on disk other than the specified path, will get open
  4. 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

  1. Infi.read() b. infi.read(24)
  2. Infi.readline() d. infi.readlines

Answer: b) infi.read(24)

 

 

9.The readlines() method returns__________

  1. a str b. a list of integers
  2. 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.

  1. ab b. rw
  2. wb d.w+

Answer : b) rw

 

 

11.Which of the following functions do you use to write data in the binary format?

  1. Write() b. output()
  2. 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>?

  1. tmpfile.read(n)
  2. tmpfile.read()
  3. tmpfile.readline()
  4. 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?

  1. outfile = open(“c:\temp.txt”, “w”)
  2. outfile = open(“c:\\temp.txt”, “wb”)
  3. outfile = open(“c:\temp.txt”, “w+”)
  4. 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.

  1. a) Pickling
  2. b) Unpickling
  3. c) Dumping
  4. d) Loading

Answer: a

 

15._______ is the process of reading from a binary file

  1. a) Pickling
  2. b) Unpickling
  3. c) Dumping
  4. 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

  1. a) seek()
  2. b) search()
  3. c) tell()
  4. d) print()

Answer : c

 

 

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

  1. a) seek()
  2. b) search()
  3. c) tell()
  4. 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

  1. a) True
  2. 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

  1. a) True
  2. 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?

  1. a) 0
  2. b) 1
  3. c) 2
  4. d) 3

Answer : a

 

 

  1. 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

 

 

  1. “wb” mode in file handling also can be written as

(a) w*b (b) w/b (c) w+b (d) none of these

 

 

  1. 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

 

 

  1. What is the extension of binary file

(a).dat (b).txt (c).bin (d).file

 

 

  1. 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

 

 

  1. 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+’)

 

 

  1. 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

  1. dump(data_object, file_object)
  2. dump[data_object, file_object]
  3. dump[file_object]
  4. dump[data_object]
  5. 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

  1. 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

 

 

  1. 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)

 

 

  1. 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

  1. 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’]

 

 

  1. 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

  1. 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]

  1. 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

  1. 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

  1. 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

  1. 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)

  1. . 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

  1. dump(myfile,tup1)
  2. dump(tup1, myfile)
  3. write(tup1,myfile)
  4. load(myfile,tup1)

 

 

error: Content is protected !!