Skip to content
Visual explainer 5h to learn 5 steps

Files, JSON, YAML & CLIs with argparse

Build a command-line tool that reads config files and takes arguments.

By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.

Topic 7 of 34

In short

Most automation tools read a config file, accept command-line flags and write results. Python's json, PyYAML and argparse cover all three with very little code.

Explained simply

Almost every automation tool does the same three things: read some settings, accept options when you run it, and write a result. Python has a ready-made tool for each: open() for files, json and yaml for structured data, and argparse for command-line options.

Files are opened with a with block. It works like a door that closes itself: when the block ends, the file is closed, even if something crashed in the middle. That prevents half-finished writes and "too many open files" errors.

JSON and YAML are two ways to write structured data as text. JSON is strict and is what most APIs speak. YAML is easier for humans, with indentation instead of brackets and support for comments, so it is popular for config files like Docker Compose, Kubernetes and Ansible.

argparse turns the words after your command, like --env prod --dry-run, into Python values. It also writes the --help text for you and shows a clear error when someone types an option wrong. Together these make a script feel like a real tool.

Press Play on a diagram to walk through it one step at a time.

LayersConfig precedence (top wins)
  1. 1
    CLI flags

    --env prod overrides everything below.

  2. 2
    Environment variables

    Handy in containers and CI.

  3. 3
    Config file

    config.yaml checked into the repo.

  4. 4
    Defaults in code

    Safe values used when nothing else is set.

FlowWhat happens when you run tool.py --env prod
  1. 1
    Shell splits words

    sys.argv becomes [tool.py, --env, prod]

  2. 2
    argparse parses

    Checks types and choices, or exits 2

  3. 3
    Load file

    yaml.safe_load(config.yaml)

  4. 4
    Merge layers

    Defaults, file, env vars, flags

  5. 5
    Validate

    Clear error if something is wrong

  6. 6
    Run

    Do the work, write the output

CompareJSON vs YAML for config
JSON
  • Strict syntax, no comments
  • Spoken by almost every API
  • json module is built in
  • Easy for programs to generate
YAML
  • Indentation and comments allowed
  • Used by Compose, Kubernetes, Ansible
  • Needs PyYAML (pip install pyyaml)
  • Implicit types can surprise you

In depth

Reading and writing text correctly

Always pass encoding="utf-8" to open(). Without it, the default encoding can depend on the machine's locale settings, so a file that works on your laptop may fail with UnicodeDecodeError on a server. Mode "r" reads, "w" creates the file or empties it first, "a" appends, and "x" creates only if the file does not exist yet. Add "b" for binary data such as images or gzip files.

For big files, loop over the file object: for line in f reads one line at a time, so a 5 GB log uses almost no memory, while f.read() loads everything at once. Each line keeps its trailing newline, so call line.rstrip("\n") or line.strip().

For small files pathlib is shorter: Path("notes.txt").read_text(encoding="utf-8") and write_text() open and close the file for you.

  • "w" empties the file immediately, before you write anything
  • "x" fails if the file exists, a cheap safety check
  • errors="replace" keeps reading past bad bytes in messy logs

Writing files safely with an atomic replace

If your script crashes or the disk fills up halfway through writing config.json, the file is left broken and the next run cannot read it. The safe pattern is to write the new content to a temporary file in the same folder, flush it to disk, and then call os.replace(tmp, target).

os.replace swaps the file in one step on the same filesystem: readers see either the complete old file or the complete new one, never a half-written mix. The temporary file must live on the same filesystem (so put it in the same folder) for this guarantee. Editors, package managers and databases all use this trick.

For files that other users read, check permissions too. tempfile.mkstemp and NamedTemporaryFile create files with mode 600 (owner only), so set the mode you want with os.chmod before the swap.

FlowAtomic write in four steps
  1. Step 1
    Write temp file

    In the same folder as the target

  2. Step 2
    flush and fsync

    Make sure the bytes reach the disk

  3. Step 3
    os.replace

    Swap old for new in one step

  4. Step 4
    Readers

    See old or new, never half

JSON and YAML gotchas

JSON has no comments, keys must be strings, and json.dumps fails on values like datetime. Pass default=str to turn unknown types into strings, indent=2 for readable output, and sort_keys=True for stable diffs.

YAML is friendlier but has traps. PyYAML follows YAML 1.1, where unquoted yes, no, on and off become booleans, so a country code NO turns into False. A version like 3.10 becomes the float 3.1, and 0755 is read as an octal number (493). Quote anything that must stay a string: version: "3.10".

yaml.safe_load builds only plain data (dicts, lists, strings, numbers). The full loader can create arbitrary Python objects, which is a code-execution risk with untrusted files, and since PyYAML 6 yaml.load even demands an explicit Loader argument. Use safe_load to read and safe_dump (with sort_keys=False to keep your key order) to write.

  • An empty YAML file loads as None, so write yaml.safe_load(f) or {}
  • yaml.safe_load_all reads files with several documents split by ---
  • json.load reads a file; json.loads reads a string

argparse beyond the basics

Positional arguments are required and identified by position (deploy.py web1). Options start with dashes and are optional unless you add required=True. type=int converts and checks the value, choices limits it to a fixed set, and action="store_true" makes a flag that is False unless given. action="append" lets a flag repeat: --tag a --tag b gives ["a", "b"]. Dashes become underscores, so --dry-run is read as args.dry_run.

For tools with several actions, like git, use subcommands: parser.add_subparsers(dest="cmd", required=True), then one sub-parser per action, each with its own options.

When the user makes a mistake, argparse prints the usage line and exits with code 2, which shells and CI treat as a failure. In tests, pass a list to parse_args(["--env", "dev"]) instead of reading the real command line.

MapA CLI with subcommands
infra.py
  • deploy
    • version (positional)
    • --env dev or prod
    • --dry-run
  • status
    • --host, repeatable
    • --json
  • rollback
    • --to version
    • --yes to skip the prompt

Merging config layers

A good tool reads settings from several places and lets the most specific one win: defaults in code, then the config file, then environment variables, then CLI flags. The trick is telling "the user did not pass this flag" apart from "the user passed the default value". Give CLI options default=None, and only override when the value is not None.

For nested config, a plain dict.update replaces whole sections: updating with {"db": {"host": "x"}} wipes db.port. Write a small recursive merge that walks into nested dicts instead.

Validate after merging, not before, and fail early with a clear message ("db.host is required") instead of a KeyError ten steps later. A --show-config flag that prints the final merged config, with secrets masked, saves hours of debugging.

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Read and write text files safely~1h
  2. 2
    Parse and emit JSON and YAML~1h
  3. 3
    Define arguments and flags with argparse~1h
  4. 4
    Load config with CLI overrides~1h
  5. 5
    Build a config-driven CLI tool~1h

Key points

  • Open files with a with block so they always close, even on errors.
  • Use yaml.safe_load, never yaml.load, for untrusted YAML.
  • argparse gives you --help, types and required flags for free.
  • Let CLI flags override file values so one config serves many runs.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import argparse, json, yaml

parser = argparse.ArgumentParser(description="Deploy helper")
parser.add_argument("--config", default="config.yaml")
parser.add_argument("--env", choices=["dev", "prod"])
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()

with open(args.config) as f:
    cfg = yaml.safe_load(f) or {}
if args.env:
    cfg["env"] = args.env
cfg["dry_run"] = args.dry_run
print(json.dumps(cfg, indent=2))

Load YAML config, apply CLI overrides, print as JSON.

Update one value in a JSON state file safely

Your deploy tool keeps the last deployed time in state.json, and other scripts read that file. Step 1: read and parse the current file. Step 2: change the value in memory. Step 3: create a temporary file in the same folder with tempfile.mkstemp. Step 4: write, flush and fsync so the data really reaches the disk. Step 5: os.replace swaps it in. If the script dies at any point, state.json is still the complete old version.

python
import json, os, tempfile
from pathlib import Path

path = Path("state.json")
data = json.loads(path.read_text(encoding="utf-8"))
data["last_deploy"] = "2026-11-10T09:00:00Z"

fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
with os.fdopen(fd, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
    f.flush()
    os.fsync(f.fileno())
os.chmod(tmp, 0o644)
os.replace(tmp, path)

Defaults, YAML file, env var and flag in one loader

Step 1: start from safe defaults in code. Step 2: deep-merge the YAML file on top, so a file that sets only db.host keeps the default db.port. Step 3: let the APP_ENV environment variable override env, which is handy in containers. Step 4: let --workers override everything, but only if it was actually passed (default=None). Try it with and without --workers and with APP_ENV=prod set.

python
import argparse, os, yaml

DEFAULTS = {"env": "dev", "workers": 2, "db": {"host": "localhost", "port": 5432}}

def merge(base, extra):
    out = dict(base)
    for k, v in extra.items():
        both_dicts = isinstance(v, dict) and isinstance(out.get(k), dict)
        out[k] = merge(out[k], v) if both_dicts else v
    return out

p = argparse.ArgumentParser()
p.add_argument("--workers", type=int)
args = p.parse_args()
with open("config.yaml", encoding="utf-8") as f:
    cfg = merge(DEFAULTS, yaml.safe_load(f) or {})
cfg["env"] = os.environ.get("APP_ENV", cfg["env"])
if args.workers is not None: cfg["workers"] = args.workers

Quick reference

  • open(path, encoding="utf-8") avoids surprises from the server's locale
  • for line in f: reads a huge file one line at a time
  • json.dumps(obj, indent=2, default=str) prints readable JSON even with dates
  • yaml.safe_load(f) or {} also handles an empty YAML file
  • Quote YAML values like "3.10", "no" and "0755" so they stay strings
  • action="store_true" makes a flag; --dry-run is read as args.dry_run
  • argparse exits with code 2 on bad arguments, so CI notices
  • Write to a temp file in the same folder, then os.replace() it over the target

Common mistakes

  • Using yaml.load on untrusted input, which can run arbitrary code.
  • Opening files relative to the current directory instead of the script's location.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What happens to config.txt the moment you call open("config.txt", "w")?

Question 2

2With PyYAML, what does the line country: NO load as?

Question 3

3Which argparse setting makes --verbose a simple on/off flag?

Question 4

4Why give CLI options default=None when merging them with a config file?

Question 5

5Why should the temporary file sit in the same folder as the target for an atomic replace?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Read hosts.yaml, which contains a list under the key hosts, and print it as pretty JSON.

  2. Exercise 2medium

    Write count_errors.py that takes a log file path and an optional --level (default ERROR) and prints how many lines contain that level. Exit with code 1 and a clear message if the file does not exist.

  3. Exercise 3hard

    Build a loader with the order defaults < config.yaml < APP_* environment variables < CLI flags. Add --show-config, which prints the merged result as JSON with any key named password masked.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use JSON, YAML or TOML for config files?
YAML is the norm in the DevOps world, JSON is best for data exchanged between programs, and TOML is used by pyproject.toml. Python 3.11 and later can read TOML with the built-in tomllib module.
What is the difference between json.load and json.loads?
json.load reads from an open file object; json.loads parses a string. The same pair exists for writing: json.dump and json.dumps.
Are click or typer better than argparse?
They are popular third-party libraries with nicer syntax for big CLIs. argparse is built in, needs no install, and is perfectly fine for most automation tools.
Why does my script fail to find config.yaml when cron runs it?
cron starts in a different working folder. Build the path from the script's location, Path(__file__).resolve().parent / "config.yaml", or pass an absolute path.

Go deeper

ShareXLinkedInWhatsApp