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.

CharacterMeaning
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.


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

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