Files, JSON & YAML
Read and write files and structured config formats — the bread and butter of automation.
Theory
Most automation reads config and writes results. Python makes this easy:
- Files: open with a
withblock so they close automatically even on error - JSON: the built-in
jsonmodule ↔ dicts/lists (json.load,json.dumps) - YAML: via
pyyaml(yaml.safe_load) — common for Kubernetes/CI config
json.dumps(obj, indent=2) pretty-prints; yaml.safe_load (not load) avoids
executing arbitrary tags from untrusted files.
Real-World Example
import json
# Read JSON config, modify, write it back pretty-printed
with open("config.json") as f:
cfg = json.load(f)
cfg["replicas"] = cfg.get("replicas", 1) + 1
with open("config.json", "w") as f:
json.dump(cfg, f, indent=2)
# YAML (needs: pip install pyyaml)
import yaml
with open("deploy.yaml") as f:
spec = yaml.safe_load(f)
print(spec["kind"]) Hands-On Exercise
- Read a text file line by line and count non-empty lines.
- Load a JSON file, add a key, and write it back with indentation.
- Parse a YAML file with
yaml.safe_loadand print one nested value. - Explain why a
withblock is preferred over manually callingopen/close.
Cheat Sheet▾
| Task | Code |
|---|---|
| Read file | with open(p) as f: data = f.read() |
| Write file | with open(p, "w") as f: f.write(s) |
| Parse JSON | json.load(f) / json.loads(s) |
| Dump JSON | json.dump(o, f, indent=2) |
| Parse YAML | yaml.safe_load(f) |
| Append mode | open(p, "a") |
Common Interview Questions▾
Why use a with block to open files?
It’s a context manager that guarantees the file is closed when the block exits, even if an exception occurs — preventing leaked file handles.
Why prefer yaml.safe_load over yaml.load?
safe_load only constructs basic Python types, avoiding arbitrary code/object execution that the full loader allows from untrusted YAML.
Official Documentation
📝 My notes on this topic
Auto-saves as you type