cbse cs logo


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

Binary File in Python

● Binary file(used to store binary data such as images, video files, audio files etc.) is a non-text file. It contains data as 1s and 0s(computer readable format).
● Binary files are processed byte by byte.
● There is no delimiter and EOL character in the binary file.
● Binary files are faster in processing and consumes less memory compared to text files.
● Extension of binary files .bin(.dat allowed?)
● pickle module is offering functions(dump and load) to operating binary files.
● File opening mode must attach ‘b’ to it for operating binary file(Ex: ‘rb’- for reading)

Basic operations with binary files:
a. Reading data from a file
b. Writing data to a file
c. Appending data to a file
d. Deleting a file

When we want to write and read list, dictionary etc. then we have to use a module in python known as pickle.

The pickle module is used for implementing binary protocols for serializing and de-serializing a Python object structure.

Pickling: It is a process where a Python object hierarchy is converted into a byte stream.

Unpickling: It is the inverse of Pickling process where a byte stream is converted into an object hierarchy.

open using file open modes
• rb, rb+
• wb, wb+
• ab, ab+


import pickle  

Module Interface functions:

pickle.dump(data, fileObject) – This function is called to serialize an object hierarchy.

data = pickle.load(fileObject) – This function is called to de-serialize a data stream

Writing list in file
 Write a program to create a list L and store it to binary file “test”
Ans. import pickle as p
with open(‘test’,’wb’) as f:

Reading file : Unpickle a list
Write a program to read the data from Binary File “test” and display on screen
Ans. import pickle as p
with open(‘test’,’rb’) as f:
[‘a’, ‘b’, ‘c’, ‘d’]

Write a program to add records in pickle file ‘student’ with the following fields
name of students
marks of subject 1
marks of subject 2
marks of subject 3
sum of marks of all subjcts

import pickle as p

while ch==’Y’ :
      roll=int(input(“enter rollno”))
      name=input(“enter name”)

      sub1=int(input(“enter marks of subject1:”))

      sub2=int(input(“enter marks of subject2:”))
      sub3=int(input(“enter marks of subject3:”))
      ch=input(“do u want to add more records”).upper()
with open(‘student’,’wb’) as f:


enter rollno 3
enter name c
enter marks of subject1:34
enter marks of subject2:56
enter marks of subject3:78
do u want to add more records n

Searching in file

Write a program to search for the details (name,total) of student which roll no is read during the execution of the program.

import pickle as p
roll=int(input(“enter rollno to serarch”))
with open(‘student’,’rb’) as f:
       for r in L:
             if r[0]==roll:
                 print(“not found”)
enter rollno to serarch 1
name= a
Total= 132
enter rollno to serarch 2
name= b
Total= 198
enter rollno to serarch 4
not found

Modify records:

Write a program to update the file with a new value of Name. The values of name and rollno are read duringthe execution of the program.

import pickle as p
roll=int(input(‘enter rollno to modfiy the name’))
with open(‘student’,’rb’) as f:

for r in L:

             if r[0]==roll:
                   print(“name is”,r[1])
                   r[1]=input(“enter new name :”)
if temp==False:
       print(‘record not found’)
       with open(‘student’,”wb”) as f:

#print data after modification
with open(‘student’,’rb’) as f2:
for r in L:
           print(r[0],’\t’,r[1],’\t’,r[5]) #or print(r[0],r[1],r[5],sep=”\t”)
enter rollno to modfiy the name5
record not found
enter rollno to modfiy the name2
name is b
enter new name :z

Write data to a Binary File:
str1= “My First Binary File”
str2= str1.encode (“ASCII”)
fout.close( ) Output:test1.dat file My First Binary File

 Read the data from Binary File:
str1= )
str2 =str1.decode(“ASCII”)
fin.close( ) Output: My First Binary File
d) Write list to a Binary File
L1 = [23, 43, 55, 10, 90]
F= open(“test1.dat”, “wb”) F.write(bytearray(L1))
F.close() Output:test1.dat file 23 43 55 10 90
e)Read list from Binary File
F= open(“test1.dat”, “rb”) L1=list(
print(L1) Output:[23, 43, 55, 10, 90]

error: Content is protected !!