Atomically replace *path* with binary *content*.
(path: Path, content: bytes)
| 207 | |
| 208 | |
| 209 | def atomic_write_bytes(path: Path, content: bytes) -> None: |
| 210 | """Atomically replace *path* with binary *content*.""" |
| 211 | path.parent.mkdir(parents=True, exist_ok=True) |
| 212 | fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) |
| 213 | tmp_path = Path(tmp_name) |
| 214 | try: |
| 215 | with os.fdopen(fd, "wb") as fh: |
| 216 | if hasattr(os, "fchmod"): # not available on Windows |
| 217 | os.fchmod(fh.fileno(), _target_mode(path)) |
| 218 | fh.write(content) |
| 219 | fh.flush() |
| 220 | os.fsync(fh.fileno()) |
| 221 | os.replace(tmp_path, path) |
| 222 | _fsync_directory(path.parent) |
| 223 | finally: |
| 224 | tmp_path.unlink(missing_ok=True) |
| 225 | |
| 226 | |
| 227 | def atomic_write_text(path: Path, content: str, *, encoding: str = "utf-8") -> None: |
no test coverage detected