Files, JSON & YAML

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Python

Files, JSON & YAML

Beginner ⭐ 50 XP ⏱ 16 min #python#json#yaml#files

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 with block so they close automatically even on error
  • JSON: the built-in json module ↔ 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
  1. Read a text file line by line and count non-empty lines.
  2. Load a JSON file, add a key, and write it back with indentation.
  3. Parse a YAML file with yaml.safe_load and print one nested value.
  4. Explain why a with block is preferred over manually calling open/close.
🧾Cheat Sheet
TaskCode
Read filewith open(p) as f: data = f.read()
Write filewith open(p, "w") as f: f.write(s)
Parse JSONjson.load(f) / json.loads(s)
Dump JSONjson.dump(o, f, indent=2)
Parse YAMLyaml.safe_load(f)
Append modeopen(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