04 / REUSABLE DAILY OPERATIONS · LESSON 16

Publish a repeatable operations report

Write sorted CSV and summary JSON that keep unavailable systems in the totals.

15 min · learn at your pace

Count the systems you could not assess

A report that contains only successful observations can overstate coverage. This exercise accepts three statuses: healthy, attention and unavailable. Each system contributes to the total, including those with unavailable evidence. Keep those counts separate so an administrator can decide whether to fix a system or collect better evidence first.

Validate the complete assessment list before writing. Duplicate hosts would inflate totals, while an unknown status could disappear from every count. Inputs here already have normalized host identifiers and validated owner text; this function handles report structure rather than redoing collection.

Let the format library do the escaping

An owner's name can contain commas, quotes, Unicode or a newline. Joining fields with commas is not a reliable CSV writer. Use csv.DictWriter with explicit column names and open the file with newline="" and UTF-8 encoding. Consumers can then parse the report without guessing how names were escaped.

Sort systems by host and replace previous output with mode w. An empty successful run still writes the header and a zero-count summary; it must not leave yesterday's rows behind. Avoid adding the current wall-clock time here, because identical input should produce identical report bytes.

This function writes two browser files. Downloaded reports are data exports, not evidence that live changes were made or that every machine is healthy.

Try an example.py
import csv, io
output = io.StringIO(newline="")
writer = csv.DictWriter(output, fieldnames=["host","owner"])
writer.writeheader()
writer.writerow({"host":"srv-01","owner":"Zoë, Operations"})
print(output.getvalue())
YOUR TURN

Put it into practice.

Define write_operations_report(rows, output), returning a summary object. Rows contain normalized unique host, owner and status (healthy, attention or unavailable). Reject duplicate hosts or invalid statuses with ValueError before modifying output. Create the output directory as needed. Write UTF-8 systems.csv with columns host,owner,status sorted by host, and summary.json with total,healthy,attention,unavailable integer counts including zeros. Preserve input data; extra row keys are ignored. Repeated successful runs replace files, including empty runs that write only the CSV header and zero counts.

See an explained solution
One way to solve it.py
import csv, json
from pathlib import Path

def write_operations_report(rows, output):
    ordered = sorted(rows, key=lambda row: row["host"])
    seen = set()
    for row in ordered:
        if row["host"] in seen or row["status"] not in ("healthy", "attention", "unavailable"):
            raise ValueError("Invalid or duplicate assessment")
        seen.add(row["host"])
    summary = {"total": len(rows), **{status: sum(row["status"] == status for row in rows) for status in ("healthy", "attention", "unavailable")}}
    folder = Path(output)
    folder.mkdir(parents=True, exist_ok=True)
    with (folder / "systems.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=["host", "owner", "status"])
        writer.writeheader()
        writer.writerows({key: row[key] for key in ["host", "owner", "status"]} for row in ordered)
    (folder / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
    return summary

if __name__ == "__main__":
    print(write_operations_report([{"host":"srv-01","owner":"Operations","status":"unavailable"}], "daily-report"))

The report preserves coverage gaps and uses standard CSV escaping. Stable ordering and replacement make repeated assessments comparable without accumulating obsolete rows.