以下是一个示例代码,用于遍历子目录并将所有特定扩展名的文件重命名为相同的文件名:
import os
def rename_files(root_dir, target_ext, new_filename):
for root, dirs, files in os.walk(root_dir):
for file in files:
# 检查文件扩展名是否匹配目标扩展名
if file.endswith(target_ext):
# 构建新的文件路径和文件名
old_filepath = os.path.join(root, file)
new_filepath = os.path.join(root, new_filename + target_ext)
# 重命名文件
os.rename(old_filepath, new_filepath)
print(f"重命名文件 {old_filepath} 为 {new_filepath}")
# 示例用法
root_dir = "path/to/directory" # 要遍历的根目录
target_ext = ".txt" # 目标扩展名
new_filename = "new_file" # 新文件名(不包含扩展名)
rename_files(root_dir, target_ext, new_filename)
在上述示例代码中,rename_files
函数接受三个参数:root_dir
(要遍历的根目录),target_ext
(目标扩展名)和new_filename
(新文件名)。然后,使用os.walk
函数遍历根目录及其子目录中的所有文件和文件夹。对于每个文件,检查其扩展名是否与目标扩展名匹配。如果匹配,则构建新的文件路径和文件名,然后使用os.rename
函数重命名文件。