Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
How to Merge Dicts from Two JSON Files Like a Pro
This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.
import json
from pathlib import Path
def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
"""Merge two JSON files containing dicts, with file2 overriding file1."""
data1 = json.loads(Path(file1).read_text())
data2 = json.loads(Path(file2).read_text())
merged = {**data1,…
How to Write a Dict to a Pretty JSON File with Indent in Python
Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.
import json
from pathlib import Path
data = {
"name": "Python",
"version": 3.12,
"features": ["simple", "readable", "powerful"],
"nested": {"creator": "Guido van Rossum", "year": 1991}
}
output_path = Path("output.json")
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, inden…
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.