MrFaws Docs
Learn Python

Files and Data

Work safely with paths, text, JSON, CSV, bytes and large files.

Paths and text

from pathlib import Path

data_dir = Path.home() / ".my_app"
data_dir.mkdir(parents=True, exist_ok=True)

path = data_dir / "config.txt"
path.write_text("theme=dark\n", encoding="utf-8")
content = path.read_text(encoding="utf-8")

Use pathlib instead of assembling paths with string separators. Always specify an encoding for text.

JSON and CSV

import json

settings = {"theme": "dark", "notifications": True}
with Path("settings.json").open("w", encoding="utf-8") as file:
    json.dump(settings, file, indent=2)

Validate loaded fields and types. A valid JSON document is not automatically valid application data. Use csv.DictReader for CSV files and report the row number when validation fails.

Stream large files

from hashlib import sha256

digest = sha256()
with Path("archive.zip").open("rb") as file:
    while chunk := file.read(1024 * 1024):
        digest.update(chunk)

Chunking avoids loading an entire large file into memory. For critical writes, write a temporary file and atomically replace the old file only after the new content is complete.

On this page