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 Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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