ST.
JOSEPH INTERNATIONAL SCHOOL, KODIKOTTAI
Class: XII Comp. Sci. Department: Computer Science Date of submission: 15/04/2026
Worksheet No: 2 Topic: File Handling Note:
Binary File in Python
What is Binary File ?
Binary Files 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.
Difference between Binary File and Text File
Text File Binary File
These files can be read by human These files can not be read by humans
directly directly.
Each line is terminated by a special
character , No delimiter for a line
known as EOL
Processing of file is slower than binary
Processing of file is faster than text file
file
Why Binary File in Python?
When ever we want to write a sequence like List or
Dictionary to a file then we required binary file in python.
Steps to work with Binary File in Python
1. import pickle module.
2. Open File in required mode (read, write or append).
3. Write statements to do operations like reading,
writing or appending data.
4. Close the binary file
How to write data in Binary File?
Python provides a module named pickle which help us to
read and write binary file in python.
Remember : Before writing to binary file the structure (list or
dictionary) needs to be converted in binary format. This
process of conversion is called Pickling. Reverse process
Unpickling happen during reading binary file which converts
the binary format back to readable form.
Q1. Write a function bwrite() to write list of five numbers in a
binary file?
Line wise explanation of the above code :
1. Line one is just to define our function.
2. In line 2 we are importing a module pickle which help
to read and write data to binary file.
3. In line number 3, we are opening a file named
“[Link]” in writing mode and ‘f’ is our file
object/handle.
4. Line number 4, we are declaring a list which needs to
be write in a file.
5. This line is doing the main role of writing in a file. dump
function of pickle module is used to write list in binary
file.
6. This line is simply closing the file.
7. Last line is to calling function bwrite()
Output of above program
NOTE : Above is the binary file “[Link]” which is not in
human readable format.
Q 2. Write a function bwrite() to write list of three names in
a binary file? NOTE : It can be done in the same way as
above program, just you need to change the data of list.
Solution:
def bwrite():
import pickle
f = open("[Link]", 'wb')
d = ["Amit", "Sumit", "Naina"]
[Link](d,f)
[Link]()
bwrite() # calling function
Q3. Write a program to write the following dictionary in a binary file.
d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"}
Solution:
def bwrite():
import pickle
f = open("[Link]", 'wb')
d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"}
[Link](d,f)
[Link]()
bwrite()
In binary format the “[Link]” will look like below and you
can see that data is not in much readable format.
How to read data in Binary File?
Python provides a module named pickle which help us to
read binary file in python.
Q4. Write a program to read data from file “[Link]”
(created above in Q3)
def b_read( ):
f = open("[Link]" , "rb")
import pickle
d = [Link](f)
print(d)
b_read( )
Q5. Write a function empadd() which will add a record of
employee in a binary file “[Link]” using list. Data to be
add include employee name,
employee number. Also write a function empread() which
will read all the records from the file.
def empadd(): # This function is for adding record to a file
f = open("[Link]","wb")
import pickle
d=[]
ename=input("Enter employee name")
en = int(input("Enter employee number"))
temp=[ename, en]
[Link](temp)
d1 = [Link](d,f) # This line is actually writing content to file
[Link]() #This line breaks the connection of file handle with file
def empread(): #This function is for reading data from file
f=open("[Link]","rb")
import pickle
d = [Link](f)
for i in d:
print(d)
[Link]()
empadd() # This statement is calling a function to add new record
empread() # This statement is calling a function to read all the records
Q1. A binary file “[Link]” has structure [BookNo, Book_Name,
Author, Price].
1. Write a user defined function CreateFile() to input data
for a record and add to [Link] .
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 “[Link]
import pickle
def createfile():
fobj=open("[Link]","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]
[Link](rec, fobj)
[Link]()
createfile() # This function is called just to verify result and not
required in exam
def countrec(Author):
fobj=open("[Link]", "rb")
num = 0
try:
while True:
rec=[Link](fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
[Link]()
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 “[Link]” has structure
[admission_number, Name, Percentage]. Write a
function countrec() in Python that would read contents
of the file “[Link]” 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("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
[Link]()
return num
Q3 Write a function in python to search and display
details, whose destination is “Cochin” from binary file
“[Link]”. 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("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
[Link]()
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
“[Link]”, assuming the binary file is containing
the following structure :
[Roll Number, Student Name]
import pickle
def addrec():
fobj=open("[Link]","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
[Link](rec,fobj)
[Link]()
addrec()
Q5. Write a function searchprod( pc) in python to
display the record of a particular product from a file
[Link] 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("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[0]==pc:
print(rec)
except:
[Link]()
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 “[Link]”.
import pickle
def routechange(rno):
fobj=open("[Link]","rb")
try:
while True:
rec=[Link](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:
[Link]()
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
“[Link]”. Structure of record in a file is given below
——————– – [sport name, coach name]
def countrec(sn):
num=0
fobj=open("[Link]","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=[Link](fobj)
if rec[0]==sn:
print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:
[Link]()
Q8. A binary file “[Link]” has structure [employee
id, employee name, salary]. Write a function countrec()
in Python that would read contents of the file
“[Link]” and display the details of those employee
whose salary is above 20000.
def countrec():
num=0
fobj=open("[Link]","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=[Link](fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
[Link]()
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
“[Link]”. 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 countrec():
fobj=open("[Link]","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=[Link](fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
[Link]()
countrec()# This function is called to verify the result