""" 工具函数模块 提供文件读写、路径处理等辅助功能 """ import os import shutil from typing import Optional def read_file_bytes(filepath: str) -> bytes: """ 读取文件内容(二进制) Args: filepath: 文件路径 Returns: bytes: 文件内容 """ with open(filepath, 'rb') as f: return f.read() def write_file_bytes(filepath: str, data: bytes): """ 写入文件内容(二进制) Args: filepath: 文件路径 data: 要写入的数据 """ os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True) with open(filepath, 'wb') as f: f.write(data) def read_file_text(filepath: str, encoding: str = 'utf-8') -> str: """ 读取文件内容(文本) Args: filepath: 文件路径 encoding: 编码格式 Returns: str: 文件内容 """ with open(filepath, 'r', encoding=encoding) as f: return f.read() def write_file_text(filepath: str, text: str, encoding: str = 'utf-8'): """ 写入文件内容(文本) Args: filepath: 文件路径 text: 要写入的文本 encoding: 编码格式 """ os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True) with open(filepath, 'w', encoding=encoding) as f: f.write(text) def get_file_size(filepath: str) -> int: """ 获取文件大小 Args: filepath: 文件路径 Returns: int: 文件大小(字节) """ return os.path.getsize(filepath) def file_exists(filepath: str) -> bool: """ 检查文件是否存在 Args: filepath: 文件路径 Returns: bool: 文件是否存在 """ return os.path.isfile(filepath) def ensure_dir(dirpath: str): """ 确保目录存在,不存在则创建 Args: dirpath: 目录路径 """ os.makedirs(dirpath, exist_ok=True) def copy_file(src: str, dst: str): """ 复制文件 Args: src: 源文件路径 dst: 目标文件路径 """ os.makedirs(os.path.dirname(dst) or '.', exist_ok=True) shutil.copy2(src, dst) def get_file_extension(filepath: str) -> str: """ 获取文件扩展名 Args: filepath: 文件路径 Returns: str: 文件扩展名(含点) """ return os.path.splitext(filepath)[1] def get_filename_without_ext(filepath: str) -> str: """ 获取不带扩展名的文件名 Args: filepath: 文件路径 Returns: str: 不带扩展名的文件名 """ return os.path.splitext(os.path.basename(filepath))[0]