0% found this document useful (0 votes)
35 views7 pages

Binary File Handling

Uploaded by

mdbarath08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views7 pages

Binary File Handling

Uploaded by

mdbarath08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Binary File

What is the binary file?


Generally, binary means two. In computer science, binary files are stored in a binary
format having digits 0’s and 1’s. For example, the number 9 in binary format is
represented as ‘1001’. In this way, our computer stores each and every file in a machine-
readable format in a sequence of binary digits. The structure and format of binary files
depend on the type of file. Image files have different structures when compared to audio
files. However, decoding binary files depends on the complexity of the file format.
All binary files follow a specific format. We can open some binary files in the normal
text editor but we can’t read the content present inside the file. That’s because all the
binary files will be encoded in the binary format, which can be understood only by a
computer or machine.
Binary files in Python
• Most of the files that we see in our computer system are called binary files.
Example:
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
Access modes in Binary Files
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Pickle Module
The pickle module is a built-in module that provides functions for serializing and
deserializing Python objects.
Serialization is the process of converting an object into a stream of bytes that can be
stored in a file or transmitted over a network.
Deserialization is the reverse process of converting a stream of bytes back into an object
.
The pickle module can handle most Python objects, such as lists, dictionaries, classes,
functions, etc., but not all.
To use the pickle module, we need to import it first:
import pickle
The pickle module provides two methods - dump() and load() to work with binary
files for pickling and unpickling, respectively.
The dump( ) method
The dump() method takes an object and a file object as arguments and writes the
serialized bytes of the object to the file.
The file in which data are to be dumped, needs to be opened in binary write mode (wb)
.
Syntax of dump() is as follows:
dump(data_object, file_object)
where data_object is the object that has to be dumped to the file with the file handle
named file_object.
For example, the program given below writes the record of a student (roll_no, name,
gender and marks) in the binary file named mybinary.dat using the dump(). We need to
close the file after pickling:
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
The load( ) method
The load() method takes a file object as an argument and returns the deserialized
object from the bytes read from the file.
The file to be loaded is opened in binary read (rb) mode.
Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named
file_object and is stored in a new file handle called store_object.
For example, the program given below demonstrates how to read data from the file
mybinary.dat using the load() method:
import pickle print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)

Binary File Operation


The four major operations performed using a
binary file are—
1. Inserting/Appending a record in a binary file
2. Reading records from a binary file
3. Searching a record in a binary file
4. Updating a record in a binary file
Example:
# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()

You might also like