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