Reference library

Files & data

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

2 matches
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
Files & data easy

Write CSV file with csv DictWriter in Python

Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.

csv file-writing dictwriter
Python
import csv
from pathlib import Path

fieldnames = ["name", "city", "age"]
rows = [
    {"name": "Alice", "city": "New York", "age": 30},
    {"name": "Bob", "city": "Los Angeles", "age": 25},
    {"name": "Charlie", "city": "Chicago", "age": 35},
]

path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
16 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.