Safely write content to a file using atomic write (temp file + rename). Args: path: File path content: Content to write encoding: File encoding Raises: FileSystemError: If write fails
(path: Path, content: str, encoding: str = "utf-8")
| 58 | |
| 59 | |
| 60 | def safe_write(path: Path, content: str, encoding: str = "utf-8"): |
| 61 | """ |
| 62 | Safely write content to a file using atomic write (temp file + rename). |
| 63 | |
| 64 | Args: |
| 65 | path: File path |
| 66 | content: Content to write |
| 67 | encoding: File encoding |
| 68 | |
| 69 | Raises: |
| 70 | FileSystemError: If write fails |
| 71 | """ |
| 72 | path = Path(path).expanduser().resolve() |
| 73 | temp_path = path.with_suffix(path.suffix + ".tmp") |
| 74 | |
| 75 | try: |
| 76 | # Write to temp file |
| 77 | with open(temp_path, "w", encoding=encoding) as f: |
| 78 | f.write(content) |
| 79 | |
| 80 | # Atomic rename |
| 81 | temp_path.replace(path) |
| 82 | except Exception as e: |
| 83 | # Clean up temp file if it exists |
| 84 | if temp_path.exists(): |
| 85 | temp_path.unlink() |
| 86 | raise FileSystemError(f"Cannot write to {path}: {e}") |
| 87 | |
| 88 | |
| 89 | def safe_read(path: Path, encoding: str = "utf-8") -> str: |
no test coverage detected