栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

批量重命名目录-Python程序-效果演示

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

批量重命名目录-Python程序-效果演示

代码效果演示
Gitee源码

# -*- coding: utf-8 -*-
# Version: Python 3.9.7
# Author: TRIX
# Date: 2021-09-18 11:37:04
# Use: 批量重命名文件目录 将指定文件夹下所有格式为 str1_str2_str3的文件 或 文件夹 重命名为str1Str2Str3
import os
import itertools

rootPath='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=newPath

renamePaths(rootPath+'folder_for_test')

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号