Write text atomically via a temp file and replace, cleaning up on failure.
(path: Path, content: str, encoding: str = "utf-8")
| 31 | |
| 32 | |
| 33 | def atomic_write_text(path: Path, content: str, encoding: str = "utf-8") -> None: |
| 34 | """Write text atomically via a temp file and replace, cleaning up on failure.""" |
| 35 | path = Path(path) |
| 36 | path.parent.mkdir(parents=True, exist_ok=True) |
| 37 | tmp = path.with_suffix(path.suffix + ".tmp") |
| 38 | try: |
| 39 | tmp.write_text(content, encoding=encoding) |
| 40 | tmp.replace(path) |
| 41 | except Exception: |
| 42 | if tmp.exists(): |
| 43 | try: |
| 44 | tmp.unlink() |
| 45 | except OSError: |
| 46 | pass |
| 47 | raise |
no test coverage detected