Writes string content to a file atomically using a temp file and os.replace, ensuring data integrity and preventing partial writes.
# Source: https://github.com/win4r/ClawTeam-OpenClaw | License: MIT | Copyright 2025 HKUDS
# Provided via justclaw.it.com; keep this notice with the code.
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()
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key