import os import shutil from typing import Optional, List class FileUtil: """文件操作工具类""" @staticmethod def get_file_extension(filename: str) -> Optional[str]: """获取文件扩展名 Args: filename: 文件名 Returns: 文件扩展名,如果文件没有扩展名返回None """ _, ext = os.path.splitext(filename) return ext[1:] if ext else None @staticmethod def get_file_size(filepath: str) -> Optional[int]: """获取文件大小 Args: filepath: 文件路径 Returns: 文件大小(字节),如果文件不存在返回None """ try: return os.path.getsize(filepath) except OSError: return None @staticmethod def is_file_exists(filepath: str) -> bool: """检查文件是否存在 Args: filepath: 文件路径 Returns: bool: 文件是否存在 """ return os.path.isfile(filepath) @staticmethod def create_directory(dirpath: str) -> bool: """创建目录 Args: dirpath: 目录路径 Returns: bool: 是否创建成功 """ try: os.makedirs(dirpath, exist_ok=True) return True except OSError: return False @staticmethod def list_files(dirpath: str, recursive: bool = False) -> Optional[List[str]]: """列出目录下的文件 Args: dirpath: 目录路径 recursive: 是否递归列出 Returns: 文件路径列表,如果目录不存在返回None """ if not os.path.isdir(dirpath): return None if recursive: file_list = [] for root, _, files in os.walk(dirpath): for file in files: file_list.append(os.path.join(root, file)) return file_list else: return [ f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, f)) ] @staticmethod def delete_file(filepath: str) -> bool: """删除文件 Args: filepath: 文件路径 Returns: bool: 是否删除成功 """ try: os.remove(filepath) return True except OSError: return False @staticmethod def copy_file(src: str, dst: str) -> bool: """复制文件 Args: src: 源文件路径 dst: 目标文件路径 Returns: bool: 是否复制成功 """ try: shutil.copy2(src, dst) return True except OSError: return False