有好几个文件夹,每个里面都有好几张图片,要批量对图片重命名

有几百个文件,每个文件里有两2张到5左右的图片,现在想对这些图片进行批量重命名,每个文件夹里的图片都改为资质1,资质2,吊牌1等

py 可以实现 , 就是费时间啊.. 而且你的命名规则 为啥不一致呢 , 是不是有特殊需求

可以使用Python的os和shutil模块来实现此功能。

首先,需要遍历所有文件夹,找到其中的图片文件。可以使用os模块的walk函数来实现:


import os

for root, dirs, files in os.walk('path/to/folder'):
    for file in files:
        if file.endswith('.jpg') or file.endswith('.png'):
            # 对图片进行重命名

然后,可以使用字符串的拼接来生成新的文件名,例如


new_name = '资质1.jpg'

最后,使用shutil模块的move函数来将图片重命名并移动到指定的文件夹中,例如:


import shutil

old_path = os.path.join(root, file)
new_path = os.path.join(root, new_name)
shutil.move(old_path, new_path)

将以上代码整合起来,可以得到完整的代码:


import os
import shutil

for root, dirs, files in os.walk('path/to/folder'):
    for file in files:
        if file.endswith('.jpg') or file.endswith('.png'):
            if '资质' in file or '吊牌' in file:
                continue
            if '资质1' not in file:
                new_name = '资质1' + os.path.splitext(file)[1]
            elif '资质2' not in file:
                new_name = '资质2' + os.path.splitext(file)[1]
            elif '吊牌1' not in file:
                new_name = '吊牌1' + os.path.splitext(file)[1]
            else:
                continue
            old_path = os.path.join(root, file)
            new_path = os.path.join(root, new_name)
            shutil.move(old_path, new_path)
     这个代码会遍历所有文件夹中的图片文件,如果文件名中已经包含了资质或吊牌的信息,则跳过不处理;否则,根据图片所在的文件夹不同,生成不同的新文件名,并将图片重命名并移动到所在的文件夹中。