Amit Singh
MGM Higher Secondary School BOKARO
INTRODUCTION
Most of the files that we see in our computer system are called Binary files.
|| COMPUTER SCIENCE XII ||
Example:
Executable
Image files Video files Audio files Archieve files
files
.png .mp4 .mp3 .zip .exe
.jpg .3gp .wav .rar
.dll
.gif .mkv .mka .iso
.bmp .avi .aac .7z .class
We can open some binary files in the normal text editor but we can’t read the content
present inside the file.
Because of binary format which is understandable by computer or a machine.
There is no requirement of translator.
Processing of these files are easy and fast.
In Python, pickling process is used to read, write, append and update binary files.
PICKLING IN PYTHON
Pickle is responsible for serializing and de-serializing of data.
Serializing means converting a python object (like List, Dictionary etc.) into byte
stream and de-serializing means converting the stream back to python object.
The advantage is that we can use store data in file for later use, send it over different
protocols, save the data in databases.
PICKLE MODULE
pickle.dump()
Used to write the object in a file
Syntax: pickle.dump(<structure>,file object)
Here, structure can be any sequence such as list, dictionary of Python.
And file object is the file handle of the file, in which to write.
pickle.load()
Used to read the data from a file.
Syntax: Structure=pickle.load(file object)
Here, structure can be any sequence such as list, dictionary of Python.
And file object is the file handle of the file, from which to read.
1 Page
, File Handling : Binary Files
Amit Singh
MGM Higher Secondary School BOKARO
OPERATIONS ON BINARY FILE
|| COMPUTER SCIENCE XII ||
###SIMPLE WRITE AND READ IN BINARY FORMAT ###
import pickle
def write():
f=open("Binaryfile.dat",'wb')
list=[1,2,3,4]
pickle.dump(list,f)
f.close()
def read():
f=open("Binaryfile.dat",'rb')
lst=pickle.load(f)
print(lst)
f.close()
write()
read()
###MULTIPLE RECORDS AT A SAME TIME BUT IN A SINGLE LIST
APPENDING DATA INTO THE FILE ###
import pickle
def write():
f=open("Binaryfile.dat",'wb')
Rec=[]
while True:
roll=int(input("ENTER ROLL NO.: "))
name=input("ENTER NAME OF STUDENT: ")
marks=int(input("ENTER THE TOTAL MARKS OBTAINED: "))
grade=input("ENTER THE GRADE: ")
R=[roll,name,marks,grade]
Rec.append(R)
ch=input("DO YOU WANT INSERT MORE ENTRIES (y/n): ")
if ch=='n' or ch=='N':
break
pickle.dump(Rec,f)
f.close()
def read():
f=open("Binaryfile.dat",'rb')
2
lst=pickle.load(f)
Page
print(lst)