atomic-write
A Python library that replaces a file with complete bytes, or leaves the previous bytes in place.
Python 3.9+ · no dependencies
한국어 · Install · Quick start · Reference
from atomic_write import write_json
write_json("state/quota.json", {"plan": "pro", "remaining": 42})
# Every reader sees the old file or the new one, never a partial write.
Why
os.replace renames atomically, but it does not give you a temporary file, a
flush, an fsync, mode handling, create-only semantics, or a directory sync. Every
project that writes state ends up assembling those itself, and the assemblies
disagree: some chmod the temporary file after creating it, some never fsync the
directory, some use a temporary name qualified only by the process id.
The best-known dedicated library, python-atomicwrites,
was archived in July 2022. Its overwrite flag gives race-free create-only
semantics; it does not document directory fsync or dir_fd control. This library
keeps those two contracts explicit and nothing else.
os.replace |
python-atomicwrites | atomic-write | |
|---|---|---|---|
| Same-directory temporary file | you build it | yes | yes |
| Directory fsync | no | not documented | file+directory (default) |
| Create-only that survives a race | no | overwrite=False |
overwrite=False |
| Keeps the existing mode | no | not documented | default |
dir_fd containment |
you build it | no | dir_fd= |
| Maintained | stdlib | archived 2022 | this repository |
Install
pip install feno-atomic-write
The PyPI name is feno-atomic-write because atomic-write is too close to existing projects; the import name stays atomic_write.
Or install from a checkout:
python3 -m pip install .
Quick start
Replace a file and keep its permissions:
from atomic_write import write_text
write_text("~/.config/app/token", "abc123")
Publish a claim that must not overwrite anyone else's:
from atomic_write import write_json
from pathlib import Path
write_json(Path("run/owner.json"), {"pid": 4242}, overwrite=False)
# FileExistsError when another process already claimed it.
Write inside a directory you already validated:
import os
from atomic_write import write_bytes
directory = os.open(state_dir, os.O_RDONLY)
try:
write_bytes("cursor.bin", b"\x00\x01", dir_fd=directory)
finally:
os.close(directory)
Skip the fsync where a lost file is acceptable, such as a cache:
from atomic_write import write_json
write_json("cache/quota.json", cache, durability="none")
Reference
write_text(path, text, *, encoding="utf-8", errors=None, newline=None, mode=None, overwrite=True, durability="file+directory", dir_fd=None, follow_symlinks=True) -> int
Writes text and returns the number of characters written.
write_bytes(path, data, *, mode=None, overwrite=True, durability="file+directory", dir_fd=None, follow_symlinks=True) -> int
Accepts bytes, bytearray or memoryview and returns the number of bytes
written.
write_json(path, value, **kwargs) -> int
Serializes with json.dumps before touching the filesystem, so a value that
cannot be encoded leaves the destination untouched. Accepts indent (default 2),
sort_keys (default False), ensure_ascii (default False), allow_nan
(default True), separators (default the stdlib default), default (as in
json.dumps) and newline (default "\n"; None for none). Remaining keywords
go to write_text.
atomic_path(path, **kwargs)
Context manager yielding a Staged file, published when the block exits
normally and discarded when it raises:
from atomic_write import atomic_path
with atomic_path("report.md") as staged:
for row in rows:
staged.write(row + "\n")
# report.md is replaced here, only if the loop finished.
binary=True gives a bytes stream for chunked copies, zip files or uploads.
staged.path names the temporary file and staged.sync() flushes and fsyncs it,
so a caller can check the staged bytes, or that the destination is unchanged,
before publishing. Calling staged.discard() inside the block skips the publish
and keeps the previous file:
import shutil, zipfile
with open(source, "rb") as src, atomic_path(target, binary=True, mode=0o600) as staged:
shutil.copyfileobj(src, staged)
staged.sync()
if not zipfile.is_zipfile(staged.path):
staged.discard() # target keeps its previous bytes
Contracts
| Argument | Values | Meaning |
|---|---|---|
overwrite |
True (default) |
Replace an existing file |
False |
Publish a new file; FileExistsError if it exists. Uses os.link, so of two racing creators exactly one wins |
|
durability |
none |
No fsync. A crash may lose the new file |
file |
fsync the new bytes before the rename | |
file+directory (default) |
Also fsync the directory, so the rename survives a crash | |
full |
file+directory, plus macOS F_FULLFSYNC so the bytes reach stable media, not only the drive cache |
|
mode |
int or None |
None keeps the existing file's permissions; a new file gets 0o666 minus the umask |
"umask" |
Every write gets 0o666 minus the umask, ignoring the existing mode, like a plain open(path, "w") |
|
dir_fd |
int or None |
Write relative to an open directory descriptor, using that same descriptor for the rename |
follow_symlinks |
True (default) |
Replace the link's target and keep the link |
False |
Replace the link itself |
A failed write never publishes partial bytes: the destination keeps its previous contents and the temporary file is removed. Serialization happens before the file is touched.
Two writers of the same path never share a temporary name, so a nested or
concurrent write cannot publish a file another writer is still filling. The
temporary file is always created beside the destination, whatever the process's
working directory (a launchd job runs with /).
A directory that cannot be fsynced (EINVAL or ENOTSUP on SMB or FUSE) is
skipped rather than raised, because the rename has already happened by then.
Platform notes
- Verified on macOS arm64 with CPython 3.12.
- On Windows,
follow_symlinks,dir_fdand directory fsync are not exercised;os.replaceis atomic there, and the directory sync is skipped because Windows has no directory fsync. Not verified on Windows or Linux. dir_fdis a containment tool, not a sandbox: a name containing..is still resolved by the kernel. Validate names before passing them.
Limits
- It writes single files. It does not publish a directory tree, a manifest plus its members, or a multi-file transaction.
- It does not lock. Callers that need a read-modify-write cycle own their own lock.
- It does not create parent directories.
FileNotFoundErroris raised instead. - It does not verify the bytes it wrote by reading them back;
atomic_pathwithstaged.sync()lets the caller do that before publishing.
Contributing
See CONTRIBUTING.md. Run the suite with:
python3 -m pytest tests -q
License
MIT.
Metadata
Release files for feno-atomic-write 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| feno_atomic_write-0.1.0.tar.gz | 15.8 kB | Without provenance | Details for feno_atomic_write-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| feno_atomic_write-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for feno_atomic_write-0.1.0-py3-none-any.whl |
Total release size: 25.6 kB
Release files / feno_atomic_write-0.1.0.tar.gz
| Download URL | feno_atomic_write-0.1.0.tar.gz |
|---|---|
| Size | 15.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c97514a5eb21f292e3a0870817070b995b4812d8e474788c6b3ae67070a0aa80
|
|
BLAKE2b-256 checksum How to use checksums |
b12ad7d8273b903e020b4bf1f6c0bd5db9911da066840c87896448bb09851e46
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.8
|
Release files / feno_atomic_write-0.1.0-py3-none-any.whl
| Download URL | feno_atomic_write-0.1.0-py3-none-any.whl |
|---|---|
| Size | 9.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ce60f18c0fe1c23f43673c212c94cde04d3a941bf89466a8c8c56dd63cc9f32b
|
|
BLAKE2b-256 checksum How to use checksums |
125279457dcac303228282284fa150f0b44dc41dc7f0df5ffc6659034b452f3e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.8
|
Security for feno-atomic-write 0.1.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.