Complete worked example
python
import json
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
def write_report(path, ids):
if not isinstance(ids, list) or any(not isinstance(item, str) for item in ids):
raise ValueError("identifier list required")
payload = json.dumps({"ids": ids}, ensure_ascii=False, sort_keys=True)
target, temporary = Path(path), None
try:
with NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=target.parent, prefix="." + target.name + ".", delete=False) as handle:
temporary = Path(handle.name)
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, target)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return len(ids)- Reasoning
- Write a complete temporary report beside its target, then replace the visible file and clean up a failed attempt. Compare the stated values and failure boundary before changing the implementation.