多级文件夹(图片重命名)Python

一级文件夹下有多个二级文件夹,每个二级文件夹下还有三级文件夹,三级文件夹下是要重命名的图片。

三级文件夹下是图片。

代码实现:

# coding=UTF-8
import os
import shutil
# 函数定义,设置了三个参数变量root_path,result_path,name
def ImageRename(root_path, result_path,name):
    '''
    递归函数,遍历该文档目录和子目录下的所有文件,获取其path
    '''
    list_name_0 = []
    files_0 = os.listdir(root_path)
    for file_0 in files_0:
        if os.path.isdir(root_path + '\\' + file_0):
            list_name_0.append(file_0)
            if file_0:
                # file_0文件夹日期名(一级目录)
                all_files = []
                list_name = []
                files = os.listdir(root_path + '\\' + file_0)
                # files:图片名称数组
                # file:三级目录
                for file in files:
                    print(file)
                    if os.path.isdir(root_path + '\\' + file_0 + '\\' + file):
                        list_name.append(file)
                        if file:
                            pathDir = os.listdir(root_path + '\\' + file_0 + '\\' + file)
                            for item in pathDir:
                                print(item)
                                if '.jpg' in item:
                                    source = root_path + '\\' + file_0 + '\\' + file + '\\' + item
                                    # 重命名后图片存放地址,图片重命名组成
                                    target = result_path +FirstName + file_0  +'_'+ file  +'_' + item
                                    # 重命名后图片存放地址
                                    shutil.copy(source, target)
                        else:
                            ImageRename((root_path + '\\' + file), all_files)
    return all_files
# 修改三个参数值
path = 'F:\\0\\'  # 需要重命名图片的位置
path1 = 'F:\\2\\'  # 重命名后存放地址
FirstName ='FirstName_'#前缀名称
ImageRename(path, path1,FirstName)

输出结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值