Write Binary File in Python
We created a byte_list using a sequence of values from 0 to 255 in binary form.
The bytearray() function is a built-in function in Python that takes an iterable to convert it into an array of bytes.It is an object constructor for a mutable array of bytes, like a list , but unordered. From an iterable of integers, it only accepts values in the range(256) , or the function throws a ValueError: byte must be in range(0, 256) .
We used the bytearray() function to convert the byte_list to the byte_array . To successfully write the byte_array to the file, we used Python’s try-except control flow statement. It handles errors and exceptions without disrupting the flow of the program.
We used the with keyword to wrap the code block of writing the byte_array to the bytes_array.txt file. Next, we used the open() function to open a file for reading, or writing is a built-in function in Python. It took two arguments: the filename and the mode.
The mode is an optional argument. It defaults to r (read) if it’s not specified. We specified the mode as wb to create or truncate the existing file named bytes_array.txt as binary. The write() function wrote the byte_array to the bytes_array.txt file.
Use bytes() Function
To write a binary file in Python:
- Use the bytes() function to convert the list of bytes to a bytes type object.
- Use a with clause with open() the method in write binary mode( wb )
- Use write() method to write the byte_array to the file.
How to Write to a Binary File in Python?
💬 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 f.write(bin_str) TypeError: write() argument must be str, not bytes
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.
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:
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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: