还在手动重命名文件?Python一行代码搞定!

前言

你是否遇到过这样的场景:下载了一堆文件,文件名乱七八糟,需要批量重命名?

手动一个个改?太慢了!

今天教你用Python一键批量重命名文件,效率提升100倍。

────────────────────────────────────────

方法一:os模块批量重命名

最简单的方法,使用Python内置的`os`模块。

```python

import os

设置文件夹路径

folder_path = "D:/Downloads"

获取文件夹内所有文件

files = os.listdir(folder_path)

批量重命名

for i, file in enumerate(files):

获取文件扩展名

ext = os.path.splitext(file)[1]

新文件名

new_name = f"文件_{i+1}{ext}"

重命名

os.rename(

os.path.join(folder_path, file),

os.path.join(folder_path, new_name)

)

print(f"已重命名: {file} -> {new_name}")

print("批量重命名完成!")

```

运行效果

```

已重命名: abc.txt -> 文件_1.txt

已重命名: def.jpg -> 文件_2.jpg

已重命名: ghi.png -> 文件_3.png

批量重命名完成!

```

────────────────────────────────────────

方法二:添加前缀/后缀

有时候只需要给文件名添加前缀或后缀。

```python

import os

folder_path = "D:/Downloads"

prefix = "2026_"  # 前缀

suffix = "_backup"  # 后缀

files = os.listdir(folder_path)

for file in files:

跳过文件夹

if os.path.isfile(os.path.join(folder_path, file)):

name, ext = os.path.splitext(file)

new_name = f"{prefix}{name}{suffix}{ext}"

os.rename(

os.path.join(folder_path, file),

os.path.join(folder_path, new_name)

)

print(f"已重命名: {file} -> {new_name}")

print("完成!")

```

────────────────────────────────────────

方法三:使用正则表达式替换

更灵活的方式,使用正则表达式替换文件名中的特定内容。

```python

import os

import re

folder_path = "D:/Downloads"

files = os.listdir(folder_path)

for file in files:

替换文件名中的空格为下划线

new_name = re.sub(r'\s+', '_', file)

替换特殊字符

new_name = re.sub(r'[^\w\-_\.]', '', new_name)

if new_name != file:

os.rename(

os.path.join(folder_path, file),

os.path.join(folder_path, new_name)

)

print(f"已重命名: {file} -> {new_name}")

print("完成!")

```

────────────────────────────────────────

方法四:按日期重命名

将文件按修改日期重命名。

```python

import os

from datetime import datetime

folder_path = "D:/Downloads"

files = os.listdir(folder_path)

for file in files:

file_path = os.path.join(folder_path, file)

if os.path.isfile(file_path):

获取文件修改时间

mtime = os.path.getmtime(file_path)

date_str = datetime.fromtimestamp(mtime).strftime("%Y%m%d")

获取扩展名

ext = os.path.splitext(file)[1]

新文件名

new_name = f"{date_str}_{file}"

os.rename(file_path, os.path.join(folder_path, new_name))

print(f"已重命名: {file} -> {new_name}")

print("完成!")

```

────────────────────────────────────────

完整工具脚本

把上面的代码封装成一个完整的工具:

```python

import os

import re

from datetime import datetime

def batch_rename(folder_path, mode="number", prefix="", suffix=""):

"""

批量重命名文件

参数:

folder_path: 文件夹路径

mode: 重命名模式 (number/prefix_suffix/regex/date)

prefix: 前缀

suffix: 后缀

"""

files = [f for f in os.listdir(folder_path)

if os.path.isfile(os.path.join(folder_path, f))]

for i, file in enumerate(files):

name, ext = os.path.splitext(file)

file_path = os.path.join(folder_path, file)

if mode == "number":

new_name = f"文件_{i+1:03d}{ext}"

elif mode == "prefix_suffix":

new_name = f"{prefix}{name}{suffix}{ext}"

elif mode == "regex":

new_name = re.sub(r'\s+', '_', file)

new_name = re.sub(r'[^\w\-_\.]', '', new_name)

elif mode == "date":

mtime = os.path.getmtime(file_path)

date_str = datetime.fromtimestamp(mtime).strftime("%Y%m%d")

new_name = f"{date_str}_{file}"

else:

new_name = file

if new_name != file:

os.rename(file_path, os.path.join(folder_path, new_name))

print(f"已重命名: {file} -> {new_name}")

print(f"\n完成!共处理 {len(files)} 个文件")

使用示例

if __name__ == "__main__":

按数字编号重命名

batch_rename("D:/Downloads", mode="number")

添加前缀后缀

batch_rename("D:/Downloads", mode="prefix_suffix", prefix="2026_", suffix="_backup")

按日期重命名

batch_rename("D:/Downloads", mode="date")

```

────────────────────────────────────────

总结

本文介绍了4种Python批量重命名文件的方法:

  1. **数字编号**:简单直接
  2. **前缀后缀**:灵活添加标识
  3. **正则替换**:处理特殊字符
  4. **按日期**:按时间整理

选择适合你的方式,让Python帮你提升效率!

────────────────────────────────────────

*如果对你有帮助,欢迎点赞收藏!关注我,获取更多Python自动化技巧。*

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐