How to write a binary file in Python

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.

ropen for reading (default)
wopen for writing, truncating the file first
xopen for exclusive creation, failing if the file already exists
aopen for writing, appending to the end of the file if it exists
bbinary mode
ttext 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.


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:
Write data to binary file using Python Example

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