Classes
AtomicFile
Context manager for atomic file writing.
Useful when you need to write incrementally or use file h…
AtomicFile
Context manager for atomic file writing.
Useful when you need to write incrementally or use file handle directly (e.g., with json.dump(), ElementTree.write(), etc.).
The file is written to a temporary location, then atomically renamed on successful completion. If an exception occurs, the temp file is cleaned up and the original file remains unchanged.
Internal Methods 3
__init__
Initialize atomic file writer.
__init__
def __init__(self, path: Path | str, mode: str = 'w', encoding: str | None = 'utf-8', **kwargs: Any) -> None
Initialize atomic file writer.
Parameters 3
path |
Path | str |
Destination file path |
mode |
str |
File open mode ('w', 'wb', 'a', etc.) |
encoding |
str | None |
Text encoding (default: utf-8, ignored for binary modes) **kwargs: Additional arguments passed to open() |
__enter__
Open temp file for writing.
__enter__
def __enter__(self) -> IO[Any]
Open temp file for writing.
Returns
IO[Any]
__exit__
Close temp file and rename atomically if successful.
__exit__
def __exit__(self, exc_type: type[BaseException] | None, *args: Any) -> None
Close temp file and rename atomically if successful.
Parameters 1
exc_type |
type[BaseException] | None |
Functions
atomic_write_text
Write text to a file atomically.
Uses write-to-temp-then-rename to ensure the file is never partia…
atomic_write_text
def atomic_write_text(path: Path | str, content: str, encoding: str = 'utf-8', mode: int | None = None) -> None
Write text to a file atomically.
Uses write-to-temp-then-rename to ensure the file is never partially written. If the process crashes during write, the original file (if any) remains intact.
The rename operation is atomic on POSIX systems (Linux, macOS), meaning it either completely succeeds or completely fails - there's no partial state.
Parameters 4
| Name | Type | Default | Description |
|---|---|---|---|
path |
Path | str |
— | Destination file path |
content |
str |
— | Text content to write |
encoding |
str |
'utf-8' |
Text encoding (default: utf-8) |
mode |
int | None |
None |
File permissions (default: None, keeps system default) |
atomic_write_bytes
Write binary data to a file atomically.
atomic_write_bytes
def atomic_write_bytes(path: Path | str, content: bytes, mode: int | None = None) -> None
Write binary data to a file atomically.
Parameters 3
| Name | Type | Default | Description |
|---|---|---|---|
path |
Path | str |
— | Destination file path |
content |
bytes |
— | Binary content to write |
mode |
int | None |
None |
File permissions (default: None, keeps system default) |