Read Binary File in Python
- Read a Binary File With open() Function in Python
- Read a Binary File With pathlib.Path in Python
- Read a Binary File With numpy.fromfile() Function in Python
The program or the internal processor interprets a binary file. It contains the bytes as the content. When we read a binary file, an object of type bytes is returned.
Read a Binary File With open() Function in Python
In Python, we have the open() function used to create a file object by passing its path to the function and opening a file in a specific mode, read mode by default. When we open binary files, we have to specify the b parameter when opening such files in reading, writing, or appending mode. In this tutorial, we will deal with the binary reading mode — rb .
In the code below, we will read a binary file and print a character from the file:
with open("sample.bin","rb") as f: data = f.read() print(data[2])
If we print individual characters, then we can view the integers.
Python has a package called struct , which has many methods and can be used to handle binary data stored in files, databases, and other resources.
The struct.unpack() is used to read packed data in a specified format layout. Such layout, which is used while packing and unpacking data, is specified using format characters. These format characters, along with their size, are shown below:
Note that the struct.unpack() function always returns a tuple.
import struct with open("sample.bin","rb") as f: data = f.read() unpack_result = struct.unpack('hhl', data[0:8]) print(unpack_result)