👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

你有没有遇到过这些情况:

  • 下载了100张照片,名字全是 IMG_001、IMG_002……
  • 合同文件需要统一加上日期后缀
  • 文件名里的错别字要一个个改

今天教你怎么用 python-office 批量重命名文件

1、替换文件名中的文字

把文件夹里所有文件名中的 "旧文字" 替换成 "新文字":

1
2
3
4
5
6
7
8
import office

# 替换文件名中的文字
office.file.replace(
folder='C:\\Users\\你的用户名\\Desktop\\照片',
old='IMG_',
new='照片_'
)

运行后:

  • IMG_001.jpg照片_001.jpg
  • IMG_002.jpg照片_002.jpg
  • ……

2、用正则表达式重命名

想更灵活地匹配?用正则表达式:

1
2
3
4
5
6
7
8
9
import office

# 使用正则替换
office.file.replace(
folder='合同文件夹',
old=r'(\d{4})年(\d{2})月(\d{2})日',
new=r'\1-\2-\3', # 把"2024年01月01日"改成"2024-01-01"
use_regex=True
)

3、在文件名前后加内容

1
2
3
4
5
6
7
8
9
10
11
12
13
import office

# 在所有文件名前加前缀
office.file.add_prefix(
folder='文件夹路径',
prefix='2024年_'
)

# 在所有文件名后加后缀
office.file.add_suffix(
folder='文件夹路径',
suffix='_备份'
)

4、按序号重命名

1
2
3
4
5
6
7
8
9
import office

# 给文件按顺序编号
office.file.numbering(
folder='文件夹路径',
start=1,
prefix='第',
suffix='张'
)

运行后:

  • 照片1.jpg第1张.jpg
  • 照片2.jpg第2张.jpg

5、实战案例:整理下载文件夹

每次下载完,文件夹里乱七八糟的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import office

# 整理下载文件夹
folder = 'C:\\Users\\你的用户名\\Downloads'

# 1. 把所有空格替换成下划线
office.file.replace(folder=folder, old=' ', new='_')

# 2. 删除所有重复的下划线
office.file.replace(folder=folder, old='__', new='_', use_regex=True)

# 3. 把大写改成小写
import os
for file in os.listdir(folder):
if file != file.lower():
src = os.path.join(folder, file)
dst = os.path.join(folder, file.lower())
os.rename(src, dst)

print('文件夹整理完成!')

6、实战案例:给照片加上拍摄日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import office
from datetime import date

folder = '照片文件夹'

# 获取所有jpg文件
for file in os.listdir(folder):
if file.endswith('.jpg'):
# 提取文件名中的日期
# 假设文件名是 20240115_123456.jpg(年月日_时间.jpg)
date_str = file[:8] # 取前8位日期

# 格式化日期
formatted = f"{date_str[:4]}-{date_str[4:6]}-{date_str[6:8]}"

# 重命名
new_name = f"{formatted}_{file[9:]}"
src = f"{folder}\\{file}"
dst = f"{folder}\\{new_name}"
office.file.rename(src=src, dst=dst)

print('照片日期标注完成!')

7、常见问题

Q:重命名后文件打不开了?

A:确保新文件名不包含特殊字符:\/:*?"<>|

Q:想把子文件夹里的文件也一起重命名?

A:加上 recursive=True 参数:

1
office.file.replace(folder='文件夹', old='旧', new='新', recursive=True)

Q:重命名错了怎么办?

A:python-office 不会删除原文件,只是改名,随时可以改回来。

8、下讲预告

学会了文件重命名,下一讲我们学 文件夹整理自动化——按类型、按日期自动分类文件。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!