💬 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
bin_str = b'this is a binary string' with open('my_file.bin', 'w') as f: f.write(bin_str)
Because this yields a
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?
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
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?
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.