# -*- coding: utf-8 -*-
import os
def rename_files_in_dir(directory):
for root, dirs, files in os.walk(directory):
for file in files:
old_file_path = os.path.join(root, file)
# 获取最后一层目录名作为新文件的前缀
new_prefix = os.path.basename(os.path.dirname(old_file_path)).strip()
# 拼接新文件名
base_name, ext = os.path.splitext(file)
new_file_name = f"{new_prefix}_{base_name}{ext}"
new_file_path = os.path.join(root, new_file_name)
# 旧文件前缀
old_prefix = base_name.split('_')[0] if '_' in base_name else ''
# 跳过新旧文件前缀一致的数据
if old_prefix == new_prefix:
continue
# 执行重命名操作
os.rename(old_file_path, new_file_path)
# 使用函数
file_path = r'D:\20211215\little_fAile'
rename_files_in_dir(file_path)
这段Python脚本的目的是递归地重命名位于指定目录及其子目录下的文件
最新推荐文章于 2024-09-23 16:36:59 发布