Binary File handling in Python Class 12 notes

What is a binary file?

A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length.

Binary files are not human readable and require a special program or hardware processor that knows how to read the data inside the file.

When you write a computer program, data is held in variables and in more complex data structures such as arrays, dictionaries, or lists. A binary file allows you to store this data in a form that preserves the structures used in your program.

Serialisation (Pickling) is the process of converting an object (such as a dictionary of data) into binary sequences that can be stored in a file. When the file is accessed, the binary data is retrieved from the file and deserialised (Unpickling) into objects that are exact copies of the original information.

Python provides the pickle module to achieve the purpose of Pickling and Unpickling.

Pickle module provides:

dump() function: We use dump() method to perform pickling operation on our Binary Files. It returns the object representation in byte mode. The dump() method belongs to pickle module.

Syntax:

import pickle

pickle.load(object,file)

 

load() function: In pickle module, load() function is used to read data from a binary file or file object.

Syntax:

import pickle

pickle.load(file)

 

Working with Binary File:

1) Writing to the Binary File

import pickle
def writefile():
    f=open("datafile.dat", "wb")
    list=["Apple","Mango", "Banana"]
    pickle.dump(list,f)
    f.close
writefile()
print("Writing done")

 

 

2) Reading from the Binary File

 

import pickle
def readfile():
    f=open("datafile.dat","rb")
    result=pickle.load(f)
    print(result)
    f.close()
readfile()

 

 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved
error: Content is protected !!