数据加WJ前缀

发布时间 2023-11-14 14:45:57作者: 不上火星不改名

你好,我将给你一个地址,请你遍历地址和地址下所有子文件夹,里面有很多图片名称,如"Gold watch_ Blue hexagonal dial_ Gold numbers and pointers_ Gold strap" 每个下划线作为分割的符号,下划线间的字符作为一个单元。如:“Gold watch_ Blue hexagonal dial_ Gold numbers and pointers_ Gold strap” 中就有4个单元。现在需要:针对地址及子文件下的所有图片类文件,选取第一个单元,在前方加入“WJ”并复制一份加入文件名前。变为“WJGold watch_ Gold watch_ Blue hexagonal dial_ Gold numbers and pointers_ Gold strap”.

 

import os

def rename_images_in_directory(directory):
    # 定义识别为图片的文件扩展名
    image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff'}

    for root, dirs, files in os.walk(directory):
        for file in files:
            # 检查文件扩展名是否在定义的图片扩展名集合中
            if any(file.lower().endswith(ext) for ext in image_extensions):
                old_name = os.path.join(root, file)
                name_parts = file.split('_')
                if name_parts:
                    # 在第一个单元前添加前缀"WJ"
                    new_name = 'WJ' + name_parts[0].strip() + '_' + file
                    new_name = os.path.join(root, new_name)
                    # 重命名文件
                    os.rename(old_name, new_name)
                    print(f'Renamed: {old_name} to {new_name}')

# 提示输入目录路径
directory_path = input("请输入您想处理的目录路径: ")
rename_images_in_directory(directory_path)