"""Ecriture atomique de fichiers : un crash ou une coupure de courant pendant l'ecriture ne doit jamais laisser un fichier tronque ou corrompu a la place de l'ancien, valide.""" from __future__ import annotations import os from pathlib import Path def atomic_write_bytes(path: Path, content: bytes) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp_path = path.with_name(path.name + ".tmp") with open(tmp_path, "wb") as f: f.write(content) f.flush() os.fsync(f.fileno()) # os.replace() est atomique y compris sous Windows (contrairement a os.rename(), # qui y echoue si la destination existe deja). os.replace(tmp_path, path) def atomic_write_text(path: Path, content: str, encoding: str = "utf-8") -> None: atomic_write_bytes(path, content.encode(encoding))