Handles file I/O operations.
| 8 | # ------------------------------------------------------------ |
| 9 | |
| 10 | class FileManager: |
| 11 | """Handles file I/O operations.""" |
| 12 | |
| 13 | @staticmethod |
| 14 | def ensure_directory(path: str) -> None: |
| 15 | """Create directory if it doesn't exist.""" |
| 16 | os.makedirs(path, exist_ok=True) |
| 17 | |
| 18 | @staticmethod |
| 19 | def save_json(data: Any, filepath: str) -> None: |
| 20 | """Save data as JSON to file.""" |
| 21 | with open(filepath, 'w', encoding='utf-8') as f: |
| 22 | json.dump(data, f, indent=4, ensure_ascii=False) |
| 23 | |
| 24 | @staticmethod |
| 25 | def load_json(filepath: str) -> Optional[Dict[str, Any]]: |
| 26 | """Load JSON from file, return None if file doesn't exist.""" |
| 27 | if not os.path.exists(filepath): |
| 28 | return None |
| 29 | |
| 30 | with open(filepath, 'r', encoding='utf-8') as f: |
| 31 | return json.load(f) |
| 32 | |
| 33 | @staticmethod |
| 34 | def save_text(content: str, filepath: str) -> None: |
| 35 | """Save text content to file.""" |
| 36 | with open(filepath, 'w', encoding='utf-8') as f: |
| 37 | f.write(content) |
| 38 | |
| 39 | @staticmethod |
| 40 | def load_text(filepath: str) -> str: |
| 41 | """Load text content from file.""" |
| 42 | with open(filepath, 'r', encoding='utf-8') as f: |
| 43 | return f.read() |
| 44 | |
| 45 | file_manager = FileManager() |