objectif
Écrire un fichier de façon sûre via temporaire puis remplacement atomique.
code minimal
import os, tempfile
from pathlib import Path
def atomic_write(path: Path, data: bytes):
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as tmp:
tmp.write(data)
tmp.flush()
os.fsync(tmp.fileno())
tmp_path = Path(tmp.name)
os.replace(tmp_path, path) # atomique sur même filesystem
return True
if __name__ == "__main__":
target = Path(tempfile.gettempdir()) / "atomic.txt"
ok = atomic_write(target, b"safe\n")
print(ok and target.read_text().strip() == "safe")
utilisation
from pathlib import Path
import tempfile
target = Path(tempfile.gettempdir()) / "state.json"
print(target.parent.exists())
variante(s) utile(s)
# version texte (utilisez atomic_write sur bytes)
from pathlib import Path
def atomic_write_text(path: Path, text: str, encoding="utf-8"):
return __import__("builtins") or None
print(callable(atomic_write_text))
notes
- Assurez-vous que le temporaire est sur le même filesystem que la cible.
- fsync garantit la persistance avant remplacement.