import os from typing import Optional class File: @staticmethod def read_file(file_path: str) -> Optional[str]: """ 读取文件内容 参数: file_path: 文件路径 返回: 文件内容字符串,如果出错返回None """ try: with open(file_path, 'r', encoding='utf-8') as f: return f.read() except Exception as e: print(f"读取文件 {file_path} 出错: {str(e)}") return None @staticmethod def write_file(file_path: str, content: str) -> bool: """ 写入内容到文件 参数: file_path: 文件路径 content: 要写入的内容 返回: 是否成功写入 """ try: with open(file_path, 'w', encoding='utf-8') as f: f.write(content) return True except Exception as e: print(f"写入文件 {file_path} 出错: {str(e)}") return False @staticmethod def ensure_directory_exists(dir_path: str) -> bool: """ 确保目录存在,如果不存在则创建 参数: dir_path: 目录路径 返回: 是否成功确保目录存在 """ try: os.makedirs(dir_path, exist_ok=True) return True except Exception as e: print(f"创建目录 {dir_path} 出错: {str(e)}") return False # 使用示例 if __name__ == "__main__": # 测试load_system_prompt test_content = "这是一个测试文件内容" File.write_file("test.txt", test_content) read_content = File.read_file("test.txt") print(f"读取的文件内容: {read_content}") # 测试ensure_directory_exists File.ensure_directory_exists("test_dir")