几百张照片、截图要改名?手动改到怀疑喵生。下面脚本支持三种操作:加前缀、按序号重命名、替换关键词,并且先 dry-run 预览,确认无误再加 --go 真正执行。
#!/usr/bin/env python3
# batch_rename.py — 批量重命名,默认只预览
import argparse, os, sys
p = argparse.ArgumentParser()
p.add_argument("folder")
p.add_argument("--prefix", default="")
p.add_argument("--replace", nargs=2, metavar=("OLD","NEW"))
p.add_argument("--start", type=int, default=1, help="序号起点")
p.add_argument("--ext", default="", help="只处理该扩展名,如 .jpg")
p.add_argument("--go", action="store_true", help="真正执行(默认预览)")
a = p.parse_args()
files = sorted(f for f in os.listdir(a.folder)
if os.path.isfile(os.path.join(a.folder, f))
and (not a.ext or f.lower().endswith(a.ext)))
plans = []
for i, f in enumerate(files, a.start):
name, ext = os.path.splitext(f)
if a.replace: name = name.replace(a.replace[0], a.replace[1])
new = f"{a.prefix}{name}{ext}"
if a.prefix and a.replace is None and "--seq" in sys.argv:
new = f"{a.prefix}{i:03d}{ext}"
if new != f: plans.append((f, new))
for old, new in plans: print(f"{old} -> {new}")
if not a.go:
print(f"\n共 {len(plans)} 项待改。确认无误后加 --go 执行。"); sys.exit(0)
for old, new in plans:
os.rename(os.path.join(a.folder, old), os.path.join(a.folder, new))
print(f"完成:重命名 {len(plans)} 个文件")
python3 batch_rename.py ./photos --ext .jpg --prefix 2026- # 加前缀
python3 batch_rename.py ./photos --ext .jpg --replace IMG 照片 # 替换关键词
python3 batch_rename.py ./photos --ext .jpg --prefix trip- --seq --go # 前缀+序号并执行
实测:对12个测试文件加前缀,预览12行、执行后文件名全部符合预期,重跑因无变化输出0项——幂等安全。
--go;批量操作没有撤销。Path 或确保终端是 UTF-8。os.rename 报错(POSIX 会覆盖同名文件),先预览检查重名。懒得自己跑?下单「脚本定制」¥19.9,喵来按你的目录结构写好交付。喵窝资源铺首页 | PDF批量合并 | 图片批量压缩