How to Write to a Binary File in Python?

5/5 - (2 votes)

Problem Formulation

πŸ’¬ Question: Given a binary string in your Python script, such as b'this is a binary string'. How to write the binary string to a file in Python?

For example, you may have tried a code snippet like this that will not work with file.write():

bin_str = b'this is a binary string'
with open('my_file.bin', 'w') as f:
    f.write(bin_str)

Because this yields a TypeError:

Traceback (most recent call last):
  File "C:\...\code.py", line 3, in <module>
    f.write(bin_str)
TypeError: write() argument must be str, not bytes

How to fix this?

Solution

To write a binary string to a binary file, you need to open the file in “binary write” mode using ‘wb’ as the second positional argument of the open() function. For instance, you’d write open('my_file.bin', 'wb') instead of open('my_file.bin', 'w'). Now, on the resulting file object f, you can use f.write(b'your binary string').

Here’s a minimal example that now correctly creates and writes into the binary file 'my_file.bin':

bin_str = b'this is a binary string'
with open('my_file.bin', 'wb') as f:
    f.write(bin_str)

The resulting file looks like this:

⚑ Warning: If you use file.write() method, you’ll overwrite the contents of the file completely. And Python will not ask you again if you’re sure you want to proceed. So, use this only if you’re sure you want to override the file content.

Append Binary String to Binary File

If you want to append binary data to the end of a file without overwriting its content, you can open the file in append ('a') and binary ('b') mode using the expression open('my_file.bin', 'ab'). Then use file.write(bin_str) to append the bin_str to the end of the existing file.

Here’s an example:

bin_str = b'this is a binary string'
with open('my_file.bin', 'ab') as f:
    f.write(bin_str)

After running this code snippet, the binary file now contains the same content twice — the original content hasn’t been overwritten due to the use of the append mode:

🌎 Recommended Tutorial: How to Append to the End of a File?