Skip to content
GreenSnippets

Write a file atomically

Write to a temporary file and rename it into place so readers never see a half-written file.

Python
import os
import tempfile
from pathlib import Path


def atomic_write(path, data, encoding="utf-8"):
    path = Path(path)
    fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding=encoding) as tmp:
            tmp.write(data)
            tmp.flush()
            os.fsync(tmp.fileno())
        os.replace(tmp_name, path)
    except BaseException:
        Path(tmp_name).unlink(missing_ok=True)
        raise

Example / expected output

Output
atomic_write("config.json", '{"debug": false}')

How it works

If the process crashes mid-write, a normal open(path, "w") leaves a truncated file. Writing to a temp file in the same directory and then calling os.replace is atomic on the same filesystem. fsync makes sure the bytes reach the disk before the rename.