Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

1 match
Files & data easy

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.

bytes file-writing binary-files
Python
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')}")
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.