How to Write Bytes to a File in Python with 'wb'
Write a bytearray buffer to a binary file using Python's open() in 'wb' mode, then read it back to confirm the data.
Python code
10 linesdata = bytearray([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64])
with open("output.bin", "wb") as f:
f.write(data)
with open("output.bin", "rb") as f:
content = f.read()
print(f"Written {len(data)} bytes: {content}")
print(f"As string: {content.decode('ascii')}")
Output
Written 11 bytes: b'Hello World'
As string: Hello World
How it works
Opening a file in 'wb' mode opens it for writing in binary, which expects bytes-like objects. The bytearray is a mutable sequence of bytes, and passing it to f.write() writes the raw bytes without any text encoding. After writing, we reopen the file in 'rb' mode and read the same bytes back. The decode('ascii') method converts the bytes to a string, showing that the binary file contains exactly the original content.
Common mistakes
- Using 'w' mode instead of 'wb' causes a TypeError for bytes-like objects.
- Forgetting to close the file manually when not using a context manager.
- Assuming `f.write()` returns the number of characters instead of bytes.
Variations
- Use `open('output.bin', 'wb')` without a context manager and call `f.close()` manually.
- Write bytes directly instead of a bytearray, e.g., `f.write(b'Hello World')`.
Real-world use cases
- Writing serialized objects or binary protocols (e.g., Python's `pickle` dumps) to disk.
- Storing image or audio binary data received from an API or file upload.
- Creating encrypted or compressed file formats by writing raw byte buffers.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.