代码成果演示
Gitee源码
# -*- coding: utf-8 -*-# Version: Python 3.9.7# Author: TRIX# Date: 2021-09-18 11:37:04# Use: 批量重命名文件目录 将指定文件夹下所有格局为 str1_str2_str3的文件 或 文件夹 重命名为str1Str2Str3import osimport itertoolsrootPath='D:\\[download]\\forTest\\'def makePaths(root,subFolderName='folderForTest',dirLevel=1,folderCount=1):#新建多级文件夹 用于测试 创立目录 新文件夹名字 新建目录级数 不蕴含最外层 每层新建文件夹个数 if not os.path.exists(root): os.mkdir(root)#创立高级目录 prodList=list(itertools.product([str(n+1) for n in range(folderCount)],repeat=dirLevel))#笛卡尔积 repeat 位数 #生成每个目录 for m in range(len(prodList)): fullDirPart=root#文件夹高级目录 for n in range(dirLevel):#生成第n级目录 fullDirPart+='\\'+subFolderName+''.join(prodList[m][:n+1])#文件夹残缺目录 if not os.path.exists(fullDirPart): os.makedirs(fullDirPart)#创立目录makePaths(rootPath+'folder_for_test','f_f_t',dirLevel=3,folderCount=3)def renamePaths(root): oriDirList=[] for root, dirs, files in os.walk(root): #返回该目录内的所有文件名列表 蕴含所有级目录的元组 #root是文件自身目录 相当于dirname #dirs_list是该文件夹所有目录名字的列表(不含子目录) #files_list是该文件夹所有文件名字的列表(不含子目录) for file in files:#拼接文件目录 oriDirList.append(os.path.join(root, file)) for folder in dirs:#拼接文件夹目录 oriDirList.append(os.path.join(root, folder)) newDirList=[] for index,oriDir in enumerate(oriDirList): oriDirPartList=oriDir.split('\\')#将 原门路字符串 按\切分 为列表 oriDirPartList[-1]=oriDirPartList[-1].split('_')#将文件 或 文件夹名 按_切分 为列表 for namePartIndex,namePart in enumerate(oriDirPartList[-1]): #文件名 str1_str2_str3的文件重命名为str1Str2Str3 oriDirPartList[-1][namePartIndex]=namePart.capitalize() oriDirPartList[-1]=''.join(oriDirPartList[-1]) newDirList.append('\\'.join(oriDirPartList)) pathZipList=list(zip(oriDirList,newDirList)) pathList=[] for n in pathZipList: pathObj=pathClass(n[0], len(n[0].split('\\')),n[1]) pathList.append(pathObj) pathList=sorted(pathList,key=lambda pathObj:pathObj.oriPathLevel,reverse=True)#以 oriPathLevel 反向排序 for n in pathList:#对每个目录改名 print(n.oriPath,n.newPath,n.oriPathLevel) os.rename(n.oriPath,n.newPath)#只能对相应的文件进行重命名, 不能重命名文件的下级目录名class pathClass(object):#门路类 """docstring for pathClass""" def __init__(self, oriPath,oriPathLevel,newPath):#原门路 原门路级数 新门路 self.oriPath = oriPath self.oriPathLevel = oriPathLevel self.newPath=newPathrenamePaths(rootPath+'folder_for_test')