Reading data from Binary File in Python Programming

Read File: To fetch all the information or data written in a file we need to perform read operation on a file. There are three methods are available in python programming for reading file. These available methods are:

python-video-tutorials

Ways  to Data from a Binary File?

1). Using load() method.

reading-data-from-binary-file-in-python


(i). load():
In python programming, load() method is used to read data from a binary file. It takes file object as an argument. This load() function/method belongs to pickle module.

Syntax:

#syntax_reading_data_from_binary_file

import pickle
 
pickle.load(file)  #here file is the object, must see example for better understanding


Example 1: 
To read data from binary file it is necessary to have a file first. So, I have a file created in my system as “binary.dat”. It is a binary file so it is not in proper readable format. Below is the output of file if we try to open our binary file normally in normal text editor.

binary file: binary.dat
binary-file-in-pythonNote: When we read our binary file using load() method then we will be able to read data. 

#Example_reading_data_from_binary_file

import pickle
 
def read():
    file = open("binary.dat",'rb')
    data = pickle.load(file)
    file.close()
    print(data)
 
read()

Explanation: Here “binary.dat” is the name of binary file which is already existing in out system with some data written to it. And ‘rb’ is the file opening mode ie. binary file read mode.

Output:

[1, 2, 3, 4, 5]

reading-data-from-binary-file-in-python-2
So, here our output which is in readable format.