Python批量重命名文件:一个脚本搞定杂乱文件夹

张开发
2026/4/9 1:42:41 15 分钟阅读

分享文章

Python批量重命名文件:一个脚本搞定杂乱文件夹
Python批量重命名文件一个脚本搞定杂乱文件夹你是否曾经遇到过这样的场景下载了一堆文件文件名乱七八糟手动改名改到手抽筋或者从手机导出的照片命名毫无规律找起来像大海捞针今天我们就用Python写一个批量重命名脚本让这些烦人的工作统统自动化实战场景假设我们有一个文件夹里面存放着从不同渠道下载的图片IMG_20230101_001.jpgphoto_1.png微信图片_20230101123456.jpgScreenshot_2023-01-01-12-30-45.png我们想要将它们统一重命名为项目图片_001.jpg、项目图片_002.jpg这样的格式。核心代码实现pythonimport osimport refrom pathlib import Pathdef batch_rename_files(folder_path, prefix“文件”, start_index1):“”批量重命名文件Args: folder_path: 文件夹路径 prefix: 新文件名前缀 start_index: 起始编号 # 获取文件夹中所有文件 folder Path(folder_path) if not folder.exists(): print(f错误文件夹 {folder_path} 不存在) return # 过滤出文件排除子文件夹 files [f for f in folder.iterdir() if f.is_file()] # 按修改时间排序可选 files.sort(keylambda x: x.stat().st_mtime) print(f找到 {len(files)} 个文件准备重命名...\n) # 重命名计数 count start_index for file in files: # 获取文件扩展名 extension file.suffix # 构建新文件名 new_name f{prefix}_{count:03d}{extension} new_path folder / new_name # 检查是否已存在同名文件 if new_path.exists(): print(f跳过{file.name}目标文件已存在) continue # 重命名 try: file.rename(new_path) print(f✓ {file.name} - {new_name}) count 1 except Exception as e: print(f✗ 重命名失败{file.name}错误{e}) print(f\n完成共重命名 {count - start_index} 个文件)使用示例ifname “main”:# 修改为你自己的文件夹路径target_folder “./测试图片”batch_rename_files(target_folder, prefix“项目图片”, start_index1)进阶功能按规则提取文件名有时候我们需要从原文件名中提取特定信息。比如从IMG_20230101_001.jpg中提取日期pythondef extract_date_rename(folder_path, prefix“照片”):“”从文件名中提取日期并重命名“”folder Path(folder_path)files [f for f in folder.iterdir() if f.is_file()]# 日期提取正则 date_pattern re.compile(r(\d{4})(\d{2})(\d{2})) for file in files: # 尝试匹配日期 match date_pattern.search(file.name) if match: year, month, day match.groups() # 新文件名格式照片_2023-01-01_001.jpg count files.index(file) 1 new_name f{prefix}_{year}-{month}-{day}_{count:03d}{file.suffix} try: file.rename(folder / new_name) print(f✓ {file.name} - {new_name}) except Exception as e: print(f✗ 失败{e})使用示例extract_date_rename(“./测试图片”, prefix“照片”)实用技巧添加撤销功能万一改错了怎么办我们可以记录重命名映射关系实现撤销pythonimport jsondef batch_rename_with_undo(folder_path, prefix“文件”):“”“带撤销功能的批量重命名”“”folder Path(folder_path)files [f for f in folder.iterdir() if f.is_file()]# 记录映射关系 rename_map {} for index, file in enumerate(files, start1): new_name f{prefix}_{index:03d}{file.suffix} new_path folder / new_name rename_map[new_name] file.name try: file.rename(new_path) print(f✓ {file.name} - {new_name}) except Exception as e: print(f✗ 失败{e}) # 保存映射关系到文件 with open(folder / rename_map.json, w, encodingutf-8) as f: json.dump(rename_map, f, ensure_asciiFalse, indent2) print(f\n映射关系已保存到 rename_map.json)def undo_rename(folder_path):“”“撤销上次重命名”“”folder Path(folder_path)map_file folder / “rename_map.json”if not map_file.exists(): print(未找到重命名记录文件) return with open(map_file, r, encodingutf-8) as f: rename_map json.load(f) for new_name, old_name in rename_map.items(): new_path folder / new_name old_path folder / old_name try: new_path.rename(old_path) print(f✓ 撤销{new_name} - {old_name}) except Exception as e: print(f✗ 撤销失败{e}) # 删除映射文件 map_file.unlink() print(\n撤销完成)递归处理子文件夹pythondef batch_rename_recursive(root_path, prefix“文件”):“”“递归处理所有子文件夹”“”root Path(root_path)# 递归获取所有文件 all_files [f for f in root.rglob(*) if f.is_file()] print(f共找到 {len(all_files)} 个文件) # 按文件夹分组 folders {} for file in all_files: parent file.parent if parent not in folders: folders[parent] [] folders[parent].append(file) # 逐个文件夹处理 for folder, files in folders.items(): print(f\n处理文件夹{folder}) for index, file in enumerate(files, start1): new_name f{prefix}_{index:03d}{file.suffix} file.rename(folder / new_name) print(f ✓ {file.name} - {new_name})注意事项备份重要数据批量操作前建议先备份重要文件测试先行先用少量文件测试确认效果后再大规模使用权限问题确保有读写权限避免操作失败命名冲突处理已存在同名文件的情况特殊字符文件名中的特殊字符可能导致问题需要预处理总结通过本文的学习我们掌握了基础批量重命名的实现从文件名提取信息的高级技巧添加撤销功能提高安全性递归处理子文件夹Python让文件管理变得如此简单下次再遇到乱七八糟的文件夹就让它来帮你吧。

更多文章