import os import re def extract_chapter_number(filename): """ 从文件名中提取章节号(支持"第15.5章"、"第16章"等格式) 返回:提取到的章节号字符串(如"15.5"、"16"),若未提取到返回None """ # 正则匹配"第X章",X可以是整数或小数(如15.5) pattern = r"第(\d+(\.\d+)?)章" match = re.search(pattern, filename) if match: return match.group(1) return None def rename_chapter_files(): """主函数:遍历当前目录文件并按规则重命名""" # 获取当前脚本所在目录(也可手动指定路径,如 target_dir = r"D:\章节文件") target_dir = os.getcwd() # 遍历目录下所有文件(排除文件夹) for filename in os.listdir(target_dir): file_path = os.path.join(target_dir, filename) if os.path.isdir(file_path): # 跳过文件夹 continue # 提取章节号 chapter_num = extract_chapter_number(filename) if not chapter_num: print(f"跳过:{filename} - 未识别到有效章节号(格式需包含'第X章')") continue # 计算新章节号 try: new_chapter_num = None if chapter_num == "15.5": new_chapter_num = 16 else: # 转为数字判断 num = float(chapter_num) if num.is_integer(): # 确保是整数(如16→16,而非16.0) num = int(num) if num <= 15: new_chapter_num = num else: new_chapter_num = num + 1 else: print(f"跳过:{filename} - 章节号{chapter_num}不是整数/15.5(仅支持这两类)") continue except ValueError: print(f"跳过:{filename} - 章节号{chapter_num}不是有效数字") continue # 构造新文件名(替换原章节号) old_pattern = f"第{chapter_num}章" new_pattern = f"第{new_chapter_num}章" new_filename = filename.replace(old_pattern, new_pattern) # 执行重命名(避免重名/文件相同的情况) if new_filename == filename: print(f"跳过:{filename} - 无需修改(章节号未变化)") continue old_path = os.path.join(target_dir, filename) new_path = os.path.join(target_dir, new_filename) # 检查新文件名是否已存在 if os.path.exists(new_path): print(f"失败:{filename} - 新文件名{new_filename}已存在,无法重命名") continue # 执行重命名 try: os.rename(old_path, new_path) print(f"成功:{filename} → {new_filename}") except Exception as e: print(f"失败:{filename} - 重命名出错:{str(e)}") if __name__ == "__main__": print("===== 章节文件重命名工具 =====") print("规则:15.5章→16章,16章及以后+1,1-15章不变") print("-" * 30) rename_chapter_files() print("-" * 30) print("重命名操作完成!按任意键退出...") input() # 暂停窗口,方便查看结果