import os class FileManager: def __init__(self, workspace_id, base_dir="workspaces"): self.workspace_id = workspace_id self.base_dir = base_dir self.workspace_path = os.path.join(base_dir, str(workspace_id)) self._ensure_workspace_dir() def _ensure_workspace_dir(self): if not os.path.exists(self.workspace_path): os.makedirs(self.workspace_path) def save_file(self, filename, content): file_path = os.path.join(self.workspace_path, filename) os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(file_path, "w", encoding="utf-8") as f: f.write(content) def read_file(self, filename): file_path = os.path.join(self.workspace_path, filename) if not os.path.exists(file_path): raise FileNotFoundError(f"文件 {filename} 不存在") with open(file_path, "r", encoding="utf-8") as f: return f.read() def delete_file(self, filename): file_path = os.path.join(self.workspace_path, filename) if os.path.exists(file_path): os.remove(file_path) def list_files(self, directory=""): dir_path = ( os.path.join(self.workspace_path, directory) if directory else self.workspace_path ) if not os.path.exists(dir_path): return [] files = [] for item in os.listdir(dir_path): item_path = os.path.join(dir_path, item) if os.path.isfile(item_path): files.append(item) elif os.path.isdir(item_path): files.extend( [ os.path.join(directory, f) for f in self.list_files(os.path.join(directory, item)) ] ) return files