How to Read a binary File with Python


In order to read a binary file in Python, we can make use of the build-in open() function.

Make sure to pass in the correct combination of the characters to the open function to read in binary.


Character Meaning
r open for reading (default)
w open for writing, truncating the file first
x open for exclusive creation, failing if the file already exists
a open for writing, appending to the end of the file if it exists
b binary mode
t text mode (default)
+ open for updating (reading and writing)

So we need a combination of two characters 1) r to open the file in read mode and 2) b to enable binary mode.


Example:
with open('data_20230703.bin', 'rb') as binary_file:
    data = binary_file.read()
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap