Safely read content from a file. Args: path: File path encoding: File encoding Returns: File content Raises: FileSystemError: If read fails
(path: Path, encoding: str = "utf-8")
| 87 | |
| 88 | |
| 89 | def safe_read(path: Path, encoding: str = "utf-8") -> str: |
| 90 | """ |
| 91 | Safely read content from a file. |
| 92 | |
| 93 | Args: |
| 94 | path: File path |
| 95 | encoding: File encoding |
| 96 | |
| 97 | Returns: |
| 98 | File content |
| 99 | |
| 100 | Raises: |
| 101 | FileSystemError: If read fails |
| 102 | """ |
| 103 | path = Path(path).expanduser().resolve() |
| 104 | |
| 105 | try: |
| 106 | with open(path, "r", encoding=encoding) as f: |
| 107 | return f.read() |
| 108 | except FileNotFoundError: |
| 109 | raise FileSystemError(f"File not found: {path}") |
| 110 | except PermissionError: |
| 111 | raise FileSystemError(f"Permission denied: Cannot read {path}") |
| 112 | except Exception as e: |
| 113 | raise FileSystemError(f"Cannot read {path}: {e}") |
| 114 | |
| 115 | |
| 116 | def get_file_size(path: Path) -> int: |
no test coverage detected