Python 文件批量重命名
在 Python 中,可以使用 os
模块或 pathlib
模块来批量重命名文件。下面是一些示例,展示如何批量重命名文件。
使用 os
模块批量重命名文件
示例:将文件名添加前缀
import os
def batch_rename(directory, prefix):
try:
for filename in os.listdir(directory):
old_path = os.path.join(directory, filename)
if os.path.isfile(old_path):
new_filename = prefix + filename
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"{old_path} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 示例调用
batch_rename('path_to_directory', 'prefix_')
示例:将文件名中的空格替换为下划线
import os
def batch_rename(directory):
try:
for filename in os.listdir(directory):
old_path = os.path.join(directory, filename)
if os.path.isfile(old_path):
new_filename = filename.replace(' ', '_')
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"{old_path} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 示例调用
batch_rename('path_to_directory')
使用 pathlib
模块批量重命名文件
示例:将文件名添加后缀
from pathlib import Path
def batch_rename(directory, suffix):
path = Path(directory)
try:
for file in path.iterdir():
if file.is_file():
new_filename = file.stem + suffix + file.suffix
new_path = file.with_name(new_filename)
file.rename(new_path)
print(f"{file} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 示例调用
batch_rename('path_to_directory', '_suffix')
示例:将文件扩展名修改为 .txt
from pathlib import Path
def batch_rename(directory):
path = Path(directory)
try:
for file in path.iterdir():
if file.is_file():
new_path = file.with_suffix('.txt')
file.rename(new_path)
print(f"{file} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 示例调用
batch_rename('path_to_directory')
综合示例
以下是一个综合示例,展示如何批量重命名文件,包括添加前缀、替换空格和更改扩展名。
import os
from pathlib import Path
# 使用 os 模块批量重命名文件
def batch_rename_os(directory, prefix, suffix, replace_space):
try:
for filename in os.listdir(directory):
old_path = os.path.join(directory, filename)
if os.path.isfile(old_path):
new_filename = filename
if replace_space:
new_filename = new_filename.replace(' ', '_')
new_filename = prefix + new_filename + suffix
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"{old_path} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 使用 pathlib 模块批量重命名文件
def batch_rename_pathlib(directory, prefix, suffix, replace_space):
path = Path(directory)
try:
for file in path.iterdir():
if file.is_file():
new_filename = file.stem
if replace_space:
new_filename = new_filename.replace(' ', '_')
new_filename = prefix + new_filename + suffix + file.suffix
new_path = file.with_name(new_filename)
file.rename(new_path)
print(f"{file} 已重命名为 {new_path}")
except Exception as e:
print(f"发生错误: {e}")
# 示例调用
batch_rename_os('path_to_directory', 'prefix_', '_suffix', True)
batch_rename_pathlib('path_to_directory', 'prefix_', '_suffix', True)
通过这些示例,你可以批量重命名文件,添加前缀或后缀,替换文件名中的空格以及更改文件扩展名。选择适合自己的方法来处理文件批量重命名任务。
License:
CC BY 4.0