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()
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!