首页 › Python 实用脚本 › 批量重命名文件
批量重命名文件
整理照片、文档时,经常需要按规则批量修改文件名。用 Python 写一个小脚本,几秒钟就能完成。
按序号重命名
from pathlib import Path
folder = Path("photos")
files = sorted(p for p in folder.iterdir() if p.suffix.lower() in {".jpg", ".png"})
for i, p in enumerate(files, start=1):
new_name = f"旅行_{i:03d}{p.suffix.lower()}"
print(f"{p.name} -> {new_name}")
p.rename(p.with_name(new_name))
先预览再执行
批量操作有风险,好的做法是先只打印计划,确认无误后再真正执行:
import sys
from pathlib import Path
def plan_renames(folder, prefix):
files = sorted(p for p in Path(folder).iterdir() if p.is_file())
return [(p, p.with_name(f"{prefix}_{i:03d}{p.suffix}")) for i, p in enumerate(files, 1)]
def main():
dry_run = "--apply" not in sys.argv
plan = plan_renames("docs", "报告")
targets = [new for _, new in plan]
if len(set(targets)) != len(targets):
sys.exit("目标文件名有重复,已取消")
for old, new in plan:
print(("[预览] " if dry_run else "") + f"{old.name} -> {new.name}")
if not dry_run:
old.rename(new)
if dry_run:
print("确认无误后加上 --apply 参数执行")
if __name__ == "__main__":
main()
正则替换文件名
import re
from pathlib import Path
for p in Path("downloads").glob("*.pdf"):
# "第3章 习题(1).pdf" -> "第03章_习题.pdf"
new = re.sub(r"第(\d+)章", lambda m: f"第{int(m.group(1)):02d}章", p.stem)
new = re.sub(r"\(\d+\)", "", new).strip().replace(" ", "_")
if new != p.stem:
p.rename(p.with_stem(new))
按修改日期归档
from datetime import datetime
from pathlib import Path
src = Path("inbox")
for p in src.iterdir():
if p.is_file():
month = datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y-%m")
target = src / month
target.mkdir(exist_ok=True)
p.rename(target / p.name)
操作重要文件前先备份。rename 在 Windows 上遇到同名文件会报错,在 Linux 上则会直接覆盖,要特别小心。练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 把目录中所有文件名里的空格替换为下划线(先预览)。
查看参考答案
from pathlib import Path
for p in Path("docs").iterdir():
if " " in p.name:
new = p.with_name(p.name.replace(" ", "_"))
print(p.name, "->", new.name)
# p.rename(new) # 确认后取消注释