如何为子目录中同名同扩展名(如.pdf)文件添加递增序号重命名?
批量文件重命名解决方案
先帮你把需求对应的文件夹结构和重命名目标梳理清楚:
目标文件夹结构(含重命名要求)
Folder 1 File 1.pdf File 2.pdf File 3.pdf Folder 2 File 1.pdf → 重命名为 *File 1-1.pdf* File 2.pdf → 重命名为 *File 2-1.pdf* File 5.pdf SubFolder 2.1 File 2.pdf → 重命名为 *File 2-2.pdf* File 4.pdf File 5.pdf → 重命名为 *File 5-1.pdf* Folder 3 File 1.pdf → 重命名为 *File 1-2.pdf* File 2.pdf → 重命名为 *File 2-3.pdf* File 4.pdf → 重命名为 *File 4-1.pdf* File 6.pdf File 7.pdf
针对这个需求,我提供两种Python实现方案,你可以根据自己的偏好选择:
方案一:精准匹配指定文件重命名
如果你需要严格按照预设的规则重命名特定文件,这个脚本最适合,它不会改动任何不在规则内的文件:
import os # 定义重命名规则:(相对文件夹路径, 原文件名) → 新文件名 rename_mapping = { ("Folder 2", "File 1.pdf"): "File 1-1.pdf", ("Folder 2", "File 2.pdf"): "File 2-1.pdf", ("Folder 2/SubFolder 2.1", "File 2.pdf"): "File 2-2.pdf", ("Folder 2/SubFolder 2.1", "File 5.pdf"): "File 5-1.pdf", ("Folder 3", "File 1.pdf"): "File 1-2.pdf", ("Folder 3", "File 2.pdf"): "File 2-3.pdf", ("Folder 3", "File 4.pdf"): "File 4-1.pdf" } # 脚本所在目录作为根目录(确保脚本和Folder1/2/3在同一层级) root_directory = "." for dir_path, _, file_names in os.walk(root_directory): # 转换为相对路径,匹配规则中的键 relative_dir = os.path.relpath(dir_path, root_directory) # 处理根目录的特殊情况 if relative_dir == ".": relative_dir = "" for file in file_names: if (relative_dir, file) not in rename_mapping: continue old_full_path = os.path.join(dir_path, file) new_full_path = os.path.join(dir_path, rename_mapping[(relative_dir, file)]) # 执行重命名 os.rename(old_full_path, new_full_path) print(f"完成重命名: {old_full_path} → {new_full_path}")
使用提示:
- 运行前一定要备份所有文件,避免意外操作导致数据丢失
- 确保脚本和你的三个主文件夹在同一目录下,否则需要修改
root_directory为文件夹所在的绝对路径
方案二:自动为重复文件名编号
如果未来可能有更多重复文件需要重命名,这个脚本会自动统计每个文件名的出现次数,然后给重复的文件加上递增编号,无需手动维护规则:
import os from collections import defaultdict root_directory = "." # 第一步:统计所有文件名的出现次数 name_counter = defaultdict(int) for dir_path, _, file_names in os.walk(root_directory): for file in file_names: file_base, file_ext = os.path.splitext(file) name_counter[file_base] += 1 # 第二步:遍历并重命名重复文件 current_instance = defaultdict(int) for dir_path, _, file_names in os.walk(root_directory): for file in file_names: file_base, file_ext = os.path.splitext(file) current_instance[file_base] += 1 # 只有出现多次的文件才重命名 if name_counter[file_base] > 1: new_file_name = f"{file_base}-{current_instance[file_base]}{file_ext}" old_path = os.path.join(dir_path, file) new_path = os.path.join(dir_path, new_file_name) os.rename(old_path, new_path) print(f"完成重命名: {old_path} → {new_path}")
这个脚本会让第一个出现的重复文件名保持原样,后续出现的依次加上-1、-2的后缀,完全匹配你当前的需求,还能应对未来新增的重复文件。
内容的提问来源于stack exchange,提问作者red
相关产品推荐
相关产品推荐

