|
经常遇到这种情况:相机导出的照片叫 IMG_0001.JPG,下载的素材叫 [高清]xxx(1).mp4,想统一改名又懒得一个个点。
写了个小脚本,核心就三行:
- import os, re
- def batch_rename(folder, pattern, replacement, dry_run=True):
- for name in os.listdir(folder):
- new = re.sub(pattern, replacement, name)
- if new == name:
- continue
- if dry_run:
- print(f'{name} -> {new}')
- else:
- os.rename(os.path.join(folder, name), os.path.join(folder, new))
复制代码
用法:
- # 先预览,不改文件
- batch_rename('./photos', r'IMG_(\d+)', r'photo_')
- # 确认没问题再执行
- batch_rename('./photos', r'IMG_(\d+)', r'photo_', dry_run=False)
复制代码
几个踩过的坑:
1. dry_run 一定要有
正则写错一次,几百个文件全乱。先打印出来看看。
2. Windows 下要注意文件名非法字符
替换结果里如果出现 \ / : * ? " < > |,os.rename 会直接抛异常。
3. 中文文件名
Python 3 默认没问题,但如果路径来自命令行参数,Windows 下建议加 encoding='utf-8'。
4. 重名会覆盖
os.rename 在目标已存在时,Linux 直接覆盖,Windows 抛错。要安全就加 os.path.exists 判断。
扩展思路:加个 --recursive 参数递归子目录,或者用 pathlib 写得更优雅(Path.rglob)。
 |
|