指定文件夹包含子文件夹重命名
import os
import shutil
import uuid
def rename_image_files(directory, prefix='Real_'):
"""
遍历目录及子目录,批量重命名图像/视频文件为 前缀+编号,避免重复、覆盖、遗漏。
"""
image_extensions = {'.txt','.jpg', '.jpeg', '.mp4', '.png', '.gif', '.bmp', '.tiff', '.webp'}
image_files = []
# 1. 收集文件
for root, _, files in os.walk(directory):
for file in files:
_, ext = os.path.splitext(file)
if ext.lower() in image_extensions:
image_files.append(os.path.join(root, file))
# 2. 排序(按路径)
image_files.sort()
# 3. 生成新文件名
new_paths = []
for idx, old_path in enumerate(image_files, start=1):
_, ext = os.path.splitext(old_path)
new_filename = f"{prefix}{idx:04d}{ext}"
new_path = os.path.join(os.path.dirname(old_path), new_filename)
new_paths.append((old_path, new_path))
# 4. 先改成临时名,防止冲突
temp_paths = []
for old_path, _ in new_paths:
temp_path = old_path + f".{uuid.uuid4().hex}.tmp"
shutil.move(old_path, temp_path)
temp_paths.append(temp_path)
# 5. 再改成目标名
for temp_path, (_, final_path) in zip(temp_paths, new_paths):
shutil.move(temp_path, final_path)
print(f"✅ {os.path.basename(final_path)}")
if __name__ == '__main__':
folder_path = r'D:\zxl_bak\ds\23'
rename_image_files(folder_path)
❤️ 转载文章请注明出处,谢谢!❤️