Atomic File Write With Temp File And Rename
An atomic file writer that stages to a temporary file in the same directory, fsyncs, and renames so readers never observe partial content.
Code
import os
import tempfile
from pathlib import Path
from typing import Union
class AtomicWriteError(RuntimeError):
"""Raised when the atomic write could not be completed."""
def atomic_write(path: Union[str, Path], payload: Union[bytes, str], mode: int = 0o644) -> None:
"""Write payload to path atomically via same-directory temp file and rename."""
dest = Path(path)
parent = dest.parent
if not parent.is_dir():
raise AtomicWriteError(f"destination directory does not exist: {parent}")
data = payload.encode("utf-8") if isinstance(payload, str) else payload
fd, tmp_name = tempfile.mkstemp(dir=str(parent), prefix=f".{dest.name}.", suffix=".tmp")
tmp = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, mode)
os.replace(tmp, dest)
except OSError as exc:
tmp.unlink(missing_ok=True)
raise AtomicWriteError(f"atomic write failed for {dest}: {exc}") from excWriting in place means a crash or a concurrent reader can observe a truncated or mixed file.
Use case: engineers writing config or state files that must never be observed half-written
Inputs / outputs
- Input: destination path, bytes or text payload, optional file mode
- Output: nothing on success; the destination contains exactly the payload
Error conditions
- destination directory missing
- rename fails across filesystems
- payload write fails mid-way
Approach
write to a unique temp file in the destination directory, flush and fsync, then os.replace which is atomic on POSIX and Windows; clean up the temp file on any failure.
Implementation
import os
import tempfile
from pathlib import Path
from typing import Union
class AtomicWriteError(RuntimeError):
"""Raised when the atomic write could not be completed."""
def atomic_write(path: Union[str, Path], payload: Union[bytes, str], mode: int = 0o644) -> None:
"""Write payload to path atomically via same-directory temp file and rename."""
dest = Path(path)
parent = dest.parent
if not parent.is_dir():
raise AtomicWriteError(f"destination directory does not exist: {parent}")
data = payload.encode("utf-8") if isinstance(payload, str) else payload
fd, tmp_name = tempfile.mkstemp(dir=str(parent), prefix=f".{dest.name}.", suffix=".tmp")
tmp = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, mode)
os.replace(tmp, dest)
except OSError as exc:
tmp.unlink(missing_ok=True)
raise AtomicWriteError(f"atomic write failed for {dest}: {exc}") from exc
Verification tests
import os
import tempfile
import unittest
from pathlib import Path
from example import atomic_write
class AtomicWriteTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dir = Path(self.tmp.name)
def tearDown(self):
self.tmp.cleanup()
def test_round_trip_writes_exact_payload(self):
target = self.dir / "state.json"
atomic_write(target, '{"a": 1}')
self.assertEqual(target.read_text(encoding="utf-8"), '{"a": 1}')
def test_no_temp_files_left_after_success(self):
target = self.dir / "config.yaml"
atomic_write(target, b"key: value\n")
leftovers = [p.name for p in self.dir.iterdir() if p.name != target.name]
self.assertEqual(leftovers, [])
def test_binary_payload_is_written_unchanged(self):
target = self.dir / "blob.bin"
atomic_write(target, bytes(range(256)))
self.assertEqual(target.read_bytes(), bytes(range(256)))
def test_missing_directory_is_rejected(self):
with self.assertRaises(RuntimeError):
atomic_write(self.dir / "missing" / "file.txt", "x")
if __name__ == "__main__":
unittest.main()
Dependencies and running
No external dependencies (standard library only).
Runtime: python >= 3.9 Entry point: python example.py
Limitations and error handling
does not fsync the parent directory (metadata durability); no locking for concurrent writers.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.