Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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)
raiseExample / expected 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.
Related snippets
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- Python Tested
Read a CSV file as dictionaries
Stream CSV rows as dicts keyed by header with csv.DictReader, handling UTF-8 BOMs and quoted commas.
- Bash
Delete files older than N days
Safely remove old log or temp files with find, previewing first and handling unusual filenames.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.

