To write bytes to a file, use ‘wb’ mode to write bytes to a new file (overwrites if the file exists). For appending bytes to an existing file, use ‘ab’ mode.
For writing bytes, you can always use a bytes object or a bytearray.
The basic syntax for writing a binary file is this:
with open('filename', 'wb') as file: file.write(byte_data)
“With statement” helps us write a file, and it automatically closes when the writing is done.
Writing raw bytes to a file
Before writing, we need to create raw bytes, and to do that, we can make a bytes object using the b”…” syntax. Then, use the with open() statement and pass “wb” argument, meaning we are writing bytes to the file.
data = b'Hello, this is a byte string.' with open('raw_file.bin', 'wb') as file: file.write(data)
Writing a Byte Array
You can define a bytearray using bytearray([]) syntax. Then, write that array in the file using “with open()” and pass “wb” as an argument.
data = bytearray([72, 101, 108, 108, 111]) # Corresponds to "Hello" # Write the bytearray to a file with open('bytearray_file.bin', 'wb') as file: file.write(data)
As shown in the above output screenshot, the file contains the binary representation of the string “Hello”.
Writing an encoded string as bytes
First, we will define a unicode text and then convert the string to a byte sequence using the .encode() method.
Then, we write that binary to a file.
hindi_text = "नमस्ते, दुनिया!" # Some Unicode text data = hindi_text.encode('utf-8') with open('namaste.bin', 'wb') as file: file.write(data)
Appending bytes to an existing file
As we previously discussed, we need to pass “ab” mode to append data to the end of the file instead of creating a new file and writing to it.
Let’s append the data to the previously written “namaste.bin” file:
more_data = b'\nThis is appended data.' with open('namaste.bin', 'ab') as file: # 'ab' = append binary file.write(more_data)
You can see that we appended the binary string at the end of the file.