Skip to main content

durablewrite

Durable, cross-platform atomic file writes for Python. Data goes to a temp file in the same directory, is flushed and fsynced, then moved onto the target with os.replace, and the directory is fsynced. A reader never sees a half-written file, and a crash leaves either the previous version or the complete new one.

Typed, standard library only, Python 3.10+, Windows and POSIX.

Install

pip install durablewrite

Usage

from durablewrite import atomic_write, write_bytes_atomic, write_json_atomic, write_text_atomic

# One-shot helpers.
write_text_atomic("notes.txt", "hello\n")
write_bytes_atomic("snapshot.bin", b"\x00\x01\x02")
write_json_atomic("config.json", {"ready": True})  # serialised before any file is touched

# Stream into a file: it is replaced only if the block finishes without an error.
with atomic_write("report.csv") as f:
    for row in rows:
        f.write(row + "\n")

with atomic_write("image.png", "wb") as f:
    f.write(data)

Options (on every writer)

Option Default Meaning
fsync "full" "none", "file" (fsync the data) or "full" (data and directory)
overwrite True False: create only if absent, atomically, else FileExistsError
preserve_mode True keep the permission bits of the file being replaced (POSIX)
permissions None explicit permission bits, e.g. 0o600
preserve_owner False keep uid and gid of the replaced file (POSIX)
follow_symlinks True write through a symlink and keep it, or replace the link itself
retry DEFAULT_RETRY bounded retry while Windows reports the target locked

New files get 0o666 minus your umask, exactly like open(). When the final mode comes from permissions or from the replaced file, the temp file is created as 0o600, so a secret is never readable by others while it is being written.

from durablewrite import NO_RETRY, RetryPolicy, SharingViolationError, write_text_atomic

write_text_atomic("cache.txt", payload, fsync="none")  # atomic, not durable
write_text_atomic("token", secret, permissions=0o600, overwrite=False)

try:
    write_text_atomic("held.txt", "x", retry=RetryPolicy(max_attempts=20, max_delay=0.2))
except SharingViolationError as exc:  # a PermissionError; target untouched
    print("still locked after", exc.attempts, "attempts")

A writer that is killed mid-write cannot remove its temp file. Clean those up at startup:

from durablewrite import cleanup_temp_files

cleanup_temp_files("data/", older_than=3600)  # only *.dwtmp files written by durablewrite

Command line

durablewrite TARGET writes standard input to TARGET atomically, like sponge. TARGET is replaced only after the input ends.

sort names.txt | durablewrite names.txt
jq '.debug = true' config.json | durablewrite --json config.json
echo "one more line" | durablewrite --append notes.txt
printf 's3cret' | durablewrite --permissions 600 --no-overwrite token.txt

Options: --append, --json (refuse invalid JSON), --fsync {none,file,full}, --no-overwrite, --permissions OCTAL, --no-follow-symlinks, --attempts N. Errors go to standard error with exit status 1, and TARGET is left as it was. If TARGET was replaced but its directory could not be fsynced, the exit status is 3. python -m durablewrite works too.

On Windows, redirecting TARGET into the command (durablewrite f < f) is refused, because the shell keeps the redirected file open and that blocks the rename; pipe it instead (type f | durablewrite f). Concurrent --append runs on one file may lose each other's lines: each run is atomic, but they do not merge.

Guarantees and limits

The short version (details and sources in GUIDE.md):

  • Atomic for readers and against process crashes on local filesystems, Windows and POSIX. Exercised by a seeded test that kills a writer process at random moments and by a multi-process concurrent writer test.
  • Durable against power loss on Linux with fsync="full". On macOS, fsync does not flush the drive cache (F_FULLFSYNC is not issued). On Windows the file data is flushed but a directory cannot be fsynced.
  • Windows: os.replace is MoveFileExW, not documented as atomic by Microsoft; tested on NTFS, not guaranteed on FAT or network shares. An open handle elsewhere blocks the rename; it is retried for about a second by default, then SharingViolationError is raised. While a rename is in flight, a concurrent open() of the target can fail with PermissionError; readers that poll should retry. A read-only target cannot be replaced on Windows.
  • After the rename, a failing directory fsync raises DirectorySyncError: the new content is in place, but the rename may not survive a power loss.
  • Replacing a file creates a new one: other hard links keep the old content, and extended attributes, ACLs and alternate data streams are not copied.

Why

Writing a file in place can corrupt it: a crash, a full disk or a concurrent reader can catch it half-written. The safe pattern (temp file in the same directory, fsync, os.replace, fsync the directory) is well known but fiddly to get right on every platform.

The options that existed each fall short:

  • atomicwrites, the de-facto package, was archived by its author in 2022 and takes no fixes.
  • boltons.fileutils.atomic_save has no Windows support.
  • The atomicfile and atomicwrite packages on PyPI are abandoned (last releases in 2020 and 2015) and neither is typed.
  • safewrite is minimal and obscure.

durablewrite does the full sequence, keeps permissions, handles Windows sharing violations, documents exactly what each platform guarantees, and ships a command-line tool.

License

MIT. See LICENSE.

Metadata

Release files for durablewrite 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for durablewrite 0.2.0
File Size Uploaded Provenance Actions
durablewrite-0.2.0.tar.gz 34.4 kB Without provenance Details for durablewrite-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for durablewrite 0.2.0
File Interpreter ABI Platform Actions
durablewrite-0.2.0-py3-none-any.whl Python 3 none any Details for durablewrite-0.2.0-py3-none-any.whl

Total release size: 53.8 kB

Release files / durablewrite-0.2.0.tar.gz

Download URL durablewrite-0.2.0.tar.gz
Size 34.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e1384d39b53a89694e347386c01ae0d8c7b2f99e3e8f30c21fa61363aaed11eb
BLAKE2b-256 checksum
How to use checksums
0146b94dda134c01f953b93036f4d8ebba960ad402fc38d59149412ae3d8ad7b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / durablewrite-0.2.0-py3-none-any.whl

Download URL durablewrite-0.2.0-py3-none-any.whl
Size 19.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e870a077e1bb9d9826dbba5f7d9f80379a34a52b1546b56c196c2d56c49d89f5
BLAKE2b-256 checksum
How to use checksums
dec50e48555212f27cb60f039dcc5b21b12db3b8bd74ab7c58a4415e983f4b3f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for durablewrite 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page