Writes string content to a file atomically using a temp file and os.replace, ensuring data integrity and preventing partial writes.
def atomic_write_text(
path: Path,
content: str,
*,
encoding: str = "utf-8",
) -> None:
"""Write *content* to *path* atomically.
A unique temporary file is created via ``mkstemp`` in the same directory
as *path*, written to, then moved into place with ``os.replace``. If
anything goes wrong the temp file is cleaned up and the original *path*
is left untouched.
"""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding=encoding) as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
retry_count = 20 if sys.platform == "win32" else 1
for attempt in range(retry_count):
try:
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key