100% found this document useful (2 votes)
6K views

Binary File Important Questions

The document discusses binary files and the pickle module in Python. It provides answers to questions about binary files, how they are used to store complex data structures, and the pickle functions used for serializing and deserializing objects to binary files. The pickle module allows Python objects to be written to a file in a binary format and reconstructed when read from the file.

Uploaded by

aakarsh29baba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
6K views

Binary File Important Questions

The document discusses binary files and the pickle module in Python. It provides answers to questions about binary files, how they are used to store complex data structures, and the pickle functions used for serializing and deserializing objects to binary files. The pickle module allows Python objects to be written to a file in a binary format and reconstructed when read from the file.

Uploaded by

aakarsh29baba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Binary File Important Questions

Q.1 What is Binary File?


Ans. Binary Files contain raw data so are not in human readable format. It can be
read by using some special tool or program. Binary files may be any of the image
format like jpeg or gif, or word, excel, ppt files etc.
Q.2 What mode you need to use to open Binary file? Also give the Syntax for
same.
Ans. While opening any binary file we have to specify ‘b’ in file opening mode.
Syntax:
f1=open(“one.bin”,”wb”)- to open the file in write mode
f1=open(“two.bin”,”rb”)- to open the file in read mode
Q.3 What is pickle module?
Ans. Pickle module provides us with the ability to serialize and deserialize objects,
i.e., to convert objects into bitstreams which can be stored into files and later be
used to reconstruct the original objects.
• Pickle library is developed using the C programming language like the python
interpreter is.
• It can save complex Python data structures.
Q.4 Why we use pickle module?
Ans.
• It is very difficult for us to write several types of objects into the binary file.
• This is very difficult task, particularly if some of the objects can have variable
lengths
• We cannot read the contents of the file later.
• To overcome this problem we use pickle module.
• It can store lists, Tuples, dictionaries, sets, classes etc.
Q. 5 What is Pickling or Serialization?
Ans. Serialization is the process of transforming data or an object in memory (RAM)
to a stream of bytes called byte streams. These byte streams in a binary file can then
be stored in a disk or in a database or sent through a network. Serialization process
is also called pickling.
Q.6 What is De-serialization or unpickling?
Ans. De-serialization or unpickling is the inverse of pickling process where a byte
stream is converted back to Python object.
Q.7 What is pickle.dump()?
Ans.
• dump() function is used to store the object data to the file.
• dump( object, filehandle )
• It takes 3 arguments.
o First argument is the object that we want to store.
o The second argument is the file object we get by opening the desired file in
write-binary (wb) mode.
o the third defines the protocol.
Q.8 What is pickle.load()?
Ans.
• load() function is used to retrieve pickled data.
• mylist = pickle.load(filehandle)
• Arguments
• The primary argument is the filehandle that you get by opening the file in read-
binary (rb) mode.
Q.9 Which of the following file types allows us to store large data files in the
computer memory?
1. Text Files
2. Binary Files
3. CSV Files
4. None of these
Ans. b
Q. 10 Write a program to write Name and Roll Nos into a binary file
Ans.
import pickle
with open ("file.dat", "wb") as F1:
while True:
op = int (input ("Enter 1 to add data, 0 to quit"))
if (op == 1):
name = input ("Enter name : ")
rollno = int (input ("Roll no : "))
pickle.dump([name,rollno],F1)
elif op == 0:
break

Q. 11 Write a program to read name and roll no from a binary file. The file has
data as list [name,rollno]
Ans.
import pickle
F1 = open ("file.dat", "rb")
while True:
try:
l = pickle.load(F1)
print (l)
except EOFError:
break
F1.close()

Q. 12 Write a code to show how a dictionary is stored as binary file.


Ans.
import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)
F1.close()

Q. 13 Write a code that reads from a file “sales.dat” which has following
information [itemcode, amount] Read from the file and find the sum of the
amount.
Ans.
import pickle
F1 = open ("sales.dat", "rb")
sum = 0
while True:
try:
l = pickle.load(F1)
sum = sum + l[1]
except EOFError:
break
print (sum)
F1.close()

Q. 14 A binary file “salary.DAT” has structure [employee id, employee name,


salary]. Write a function countrec() in Python that would read contents of the
file “salary.DAT” and display the details of those employee whose salary is
above 20000.
Ans.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()

Q.15 A file sports.dat contains information in following format [event,


participant].
Write a program that would read the contents from file and copy only those
records from sports.dat where the event name is “Athletics” in new file named
Athletics.dat
Ans.
import pickle
F1 = open ("sports.dat", "rb")
F2 = open ("athletics.dat", "wb")
sum = 0
while True:
try:
l = pickle.load(F1)
if (l[0].lower() == "athletics"):
print (l)
pickle.dump(l,F2)
except EOFError:
break
F1.close()
F2.close()

Q. 16 A binary file “STUDENT.DAT” has structure [admission_number, Name,


Percentage]. Write a function countrec() in Python that would read contents of
the file “STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of students scoring above 75%.
Ans.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
10 Important Programming Questions of Binary File Handling in Python

Q1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author,


Price].

1. Write a user defined function CreateFile() to input data for a record and
add to Book.dat .
2. Write a function CountRec(Author) in Python which accepts the Author
name as parameter and count and return number of books by the given
Author are stored in the binary file “Book.dat

import pickle
def createfile():
fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()

createfile() # This function is called just to verify result and not required in exam

def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
fobj.close()
return num

n=countrec("amit") # This function is called just to verify result and not required
in exam
print("Total records", n) # This statement is just to verify result and not required
in exam
Q2. A binary file “STUDENT.DAT” has structure [admission_number, Name,
Percentage]. Write a function countrec() in Python that would read contents of
the file “STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of students scoring above 75%.

import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num

Q3 Write a function in python to search and display details, whose destination


is “Cochin” from binary file “Bus.Dat”. Assuming the binary file is containing
the following elements in the list:

1. Bus Number
2. Bus Starting Point
3. Bus Destination

import pickle
def countrec():
fobj=open("bus.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() # This function is called just to verify result
print(n)

Q4. Write a function addrec() in Python to add more new records at the bottom
of a binary file “STUDENT.dat”, assuming the binary file is containing the
following structure :

[Roll Number, Student Name]

import pickle
def addrec():
fobj=open("student.dat","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
pickle.dump(rec,fobj)
fobj.close()
addrec()

Q5. Write a function searchprod( pc) in python to display the record of a


particular product from a file product.dat whose code is passed as an argument.
Structure of product contains the following elements [product code , product
price]

import pickle
def searchprod(pc):
fobj=open("product.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[0]==pc:
print(rec)
except:
fobj.close()
n=searchprod(1) # This function is called to verify the result

Q6. Write a function routechange(route number) which takes the Route number
as parameter and modify the route name(Accept it from the user) of passed
route number in a binary file “route.dat”.

import pickle
def routechange(rno):
fobj=open("route.dat","rb")
try:
while True:
rec=pickle.load(fobj)
if rec[0]==rno:
rn=input("Enter route name to be changed ")
rec[1]=rn
print(rec) #This statement is called to verify the change in the
record
except:
fobj.close()

routechange(1) # This function is called to verify the result

Q7. Write a function countrec(sport name) in Python which accepts the name
of sport as parameter and count and display the coach name of a sport which
is passed as argument from the binary file “sport.dat”. Structure of record in a
file is given below

[sport name, coach name]

def countrec(sn):
num=0
fobj=open("data.dat","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=pickle.load(fobj)
if rec[0]==sn:
print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:
fobj.close()

Q8. A binary file “salary.DAT” has structure [employee id, employee name,
salary]. Write a function countrec() in Python that would read contents of the file
“salary.DAT” and display the details of those employee whose salary is above
20000.

def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

Q9. Amit is a monitor of class XII-A and he stored the record of all the students
of his class in a file named “class.dat”. Structure of record is [roll number, name,
percentage]. His computer teacher has assigned the following duty to Amit.
Write a function remcount( ) to count the number of students who need remedial
class (student who scored less than 40 percent)

def remcount():
fobj=open("class.dat","rb")
try:
print("Roll No\t Name\t Percentage")
while True:
rec=pickle.load(fobj)
if rec[2]>40:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

Q10. A binary file “emp.dat” has structure [employee id, employee name]. Write
a function delrec(employee number) in Python that would read contents of the
file “emp.dat” and delete the details of those employee whose employee number
is passed as argument.

You might also like