一级文件夹下有多个二级文件夹,每个二级文件夹下还有三级文件夹,三级文件夹下是要重命名的图片。
三级文件夹下是图片。
代码实现:
# 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)
输出结果: