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.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

10 lines
Python 3.9+
data = 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

stdout
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

  1. Use `open('output.bin', 'wb')` without a context manager and call `f.close()` manually.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.