以下是一个使用Python的示例代码,可以遍历文件夹结构,并将文件重命名为与子文件夹相匹配,并保留文件扩展名:
import os
def rename_files(root_dir):
for root, dirs, files in os.walk(root_dir):
for file in files:
file_path = os.path.join(root, file)
folder_name = os.path.basename(root)
file_name, file_ext = os.path.splitext(file)
new_file_name = folder_name + file_ext
new_file_path = os.path.join(root, new_file_name)
os.rename(file_path, new_file_path)
# 使用示例
root_directory = '路径/到/你的/根目录'
rename_files(root_directory)
在上述代码中,我们使用os.walk()
函数来遍历给定的根目录及其子目录。对于每个文件,我们获取其所属的子文件夹名称,并使用os.rename()
函数将文件重命名为与子文件夹相匹配的名称。为了保留文件的扩展名,我们使用os.path.splitext()
函数将文件名和扩展名分开,并在重命名时重新组合它们。