← retour aux snippets

écriture atomique: fsync puis os.replace

Écrire un fichier de façon sûre via fichier temporaire et remplacement atomique.

python filesystem #atomic-write#fsync#replace

objectif

Écrire un fichier de façon sûre via fichier temporaire et remplacement atomique.

code minimal

import os, tempfile, pathlib

def atomic_write(path: pathlib.Path, data: bytes):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=str(path.parent))
    try:
        with os.fdopen(fd, "wb", closefd=True) as f:
            f.write(data)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
    finally:
        try: os.remove(tmp)
        except FileNotFoundError: pass

with tempfile.TemporaryDirectory() as tmpdir:
    p = pathlib.Path(tmpdir) / "out.txt"
    atomic_write(p, b"OK\n")
    print(p.read_text(encoding="utf-8").strip() == "OK")  # attendu: True

utilisation

print(True)

variante(s) utile(s)

import pathlib, tempfile
with tempfile.TemporaryDirectory() as tmp:
    p = pathlib.Path(tmp) / "a" / "b.txt"
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text("x", encoding="utf-8")
    print(p.exists())

notes

  • os.replace est atomique sur le même filesystem.
  • fsync garantit la persistance sur disque avant le swap.