In the below example we show how to read a binary file in Python.
In this example, we will take a look at how to write to a binary file.
Again we will make use of the build-in open() function, and make use of the flags that will help up write a binary file from the below table.
| 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) |
We will have to make use of the w and b characters to write in binary mode.
Example:
First let's create a binary string that we want to write to the binary file.
binary_data = b'Some data to write'
Now let's write it to a file.
with open('data_20230706.bin', 'wb') as binary_file:
binary_file.write(binary_data)

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!