文件批量重命名工具(小黑框)!!!
新手发帖,不规范的地方有很多,各路大佬手下留情{:5_92:}功能介绍:
一、文件名重组
分离出原文件名的汉字、数字、字母、文件格式、手机号、身份证号手动选择重新组合
二、 自定义文件名(固定位置修改)
1.删除
手动选择固定位置,删除固定位置的文件名
2.新增
在原文件名指定位置插入新增文件名
3.截取
截取并保留原文件名固定位置的文件名
4.生成有序序列
在原文件名指定位置插入从指定数开始的有序序列
static/image/hrline/4.gif
代码展示:
import os
import re
class fileBatching():
# 目标文件夹路径
originPath = ''
# 文件列表
fileList = []
# 文件索引信息
selectedIndexList = []
# 模式选择
selectMODE = ''
# 文件名修改信息 原文件名:新文件名
# 所有操作都是先修改infoDict属性 最后通过infoDict修改文件名
infoDict = {}
MODE = {}
ROUTE = {}
# 路由选择信息
router = ''
def __init__(self) -> None:
# 模式信息
self.MODE = {
'1':{
'name':' 原文件名重组',
'method':self.regroup,
},
'2':{
'name':' 自定义文件名',
'method':self.userDefined,
},
}
# 路由信息
self.ROUTE = {
'h':{
'MODE':' 主页面',
# 模式对应的页面
'PAGE':self.PRINTROUTE,
# 控制是否显示
'SHOW':False,
},
's':{
'MODE':' 选择文件',
'PAGE':self.SELECTFILE,
'SHOW':True,
},
'm':{
'MODE':' 选择模式',
'PAGE':self.PRINTMODE,
'SHOW':False
},
'c': {
'MODE':' 信息确认修改',
'PAGE':self.CONFIRM,
'SHOW':False
},
't':{
'MODE':' 测试页',
'PAGE':self.TESTPAGE1,
'SHOW':False
},
'e':{
'MODE':' 结束',
'PAGE':lambda : 0,
'SHOW':True
},
}
# 路由选择
self.router = 'h'
# 监听路由
@property
def router(self,route):
return route
# 监听路由
@router.setter
def router(self, route):
# h是路由选择页面 但不显示选项
if(route == 'h'):
self.ROUTE['h']['PAGE']()
else:
# 选哪个选项 调用哪个选项的页面
for i in self.ROUTE:
if(route == i and self.ROUTE['SHOW']):
self.ROUTE['PAGE']()
# -----------------------页面---------------------------
# 测试页1 测试添加页面
def TESTPAGE1(self):
print("|","测试页".center(51,"*"),"|\n")
self.router = 'h'
# 路由选项页面
def PRINTROUTE(self):
print("|","文件批量重命名工具".center(51,"*"),"|\n")
file = "文件夹: " + "未选择" if self.originPath == ''else "文件夹: " + self.originPath
mode = "模式: " + "未选择" if self.selectMODE == '' else "模式: " + self.MODE['name']
print(file)
print(mode, "\n")
for route in self.ROUTE:
if(self.ROUTE['SHOW']): print(self.ROUTE['MODE'],end=' ')
self.router = input("请选择下一步 \n")
# 重命名模式选项页面
def PRINTMODE(self):
print("|","选择重命名模式".center(51,"*"),"|")
# 打印所有模式选项
for mode in self.MODE: print(self.MODE['name'])
self.selectMODE = input("选择修改模式: \n")
# 乱输就重新输
try:self.MODE
except:self.router = 'h'
# 根据模式选择方法 更新infoDict属性
self.MODE['method']()
# 打开确认修改界面显示
self.ROUTE['c']['SHOW'] = True
# 路由
self.router = 'h'
# 文件选项页面 并设置需要重命名的文件索引
def SELECTFILE(self):
# 乱输就重新输
try:
if(self.originPath == ''):
self.originPath = input("选择文件夹路径(把文件夹拉进来或复制绝对路径 首尾不要带双引号!):\n")
fileList = self.fileList = os.listdir(self.originPath)
else:
otherFile = input(" 选择文件 选择文件夹\n")
if(otherFile == '1'):
fileList = self.fileList = os.listdir(self.originPath)
elif(otherFile == '2'):
self.originPath = input("选择文件夹路径(把文件夹拉进来!):\n")
fileList = self.fileList = os.listdir(self.originPath)
print("|","选择文件".center(51,"*"),"|")
# 序号文件名组合
fileListAndIndex = self.CreateIndexNumbers(fileList)
print(fileListAndIndex)
selected = input("请选择需要重命名的文件以英文逗号( , )隔开 星号( * )代表全选: \n")
if(',' in selected):
selected =
self.selectedIndexList = selected
# 起点-终点 (不能用于负数)
elif('-' in selected):
selected =
selectedStart = selected
selectedEnd = selected + 1
self.selectedIndexList =
elif(selected == '*'):
self.selectedIndexList =
except:
self.router = 's'
# 模式选项打开
self.ROUTE['m']['SHOW'] = True
# 路由
self.router = 'h'
# 确认页面
def CONFIRM(self):
# 打印选中的文件
fileList = self.fileList
selectfileList = []
for i in self.selectedIndexList:
selectfileList.append(fileList)
print("|","确认修改信息".center(51,"*"),"|")
for i in self.infoDict:
print(i + ' -> ' + self.infoDict)
confirm = input(" 确认 取消 \n")
if(confirm == '1'):
self.reNameFiles(fileList, self.selectedIndexList)
else:
self.router = 'h'
return 0
self.ROUTE['c']['SHOW'] = False
self.ROUTE['m']['SHOW'] = False
# 路由
self.router = 'h'
# -----------------------组件---------------------------
# 重组 修改重组信息self.infoDict
def regroup(self):
rulesList = []
self.infoDict = {}
fileList = self.fileList
selectedIndexList = self.selectedIndexList
example = fileList]
# 取例子
rulesList = rulesList + self.extractChinese(example) + self.extractNumber(example) + self.extractWord(example) + self.extractFilename(example) + self.extractID(example) + self.extractTelephoneNmber(example)
print("|","确认规则".center(51,"*"),"|")
# 打印序号选择列表
print(self.CreateIndexNumbers(rulesList))
# 生成规则 覆盖rulesList
rulesList = a b c d 规则: 023等于acd, 123等于bcd \n")]
# 确认修改信息 更新infoDict属性
for i in selectedIndexList:
it = fileList
info = ''
k = self.extractChinese(it) + self.extractNumber(it) + self.extractWord(it) + self.extractFilename(it) + self.extractID(it) + self.extractTelephoneNmber(it)
for key in rulesList:
info = info + k
self.infoDict] = info
# 自定义 修改重组信息self.infoDict
def userDefined(self):
# 操作选项
way = '1'
# 初始化infoDict
self.infoDict = {}
print("|","确认规则".center(51,"*"),"|")
way = input("选择要进行的操作: 删除 新增 截取 生成有序序列\n")
# 删除
if(way == '1'):
self.delFilename()
# 新增
elif(way == '2'):
self.newFilename()
# 截取
elif(way == '3'):
self.splitFilename()
# 生成序列
elif(way == '4'):
self.generateFilename()
else:
# 乱输就回去吧你
self.router = 'h'
# 删除
def delFilename(self):
fileList = self.fileList
selectedIndexList = self.selectedIndexList
# 取例子字符串
example = fileList]
# 例子+序号
print(self.CreateIndexNumbers(list(example)))
try:
selected = input("输入位置(起点-终点) :\n")
selected =
start = selected
end = selected + 1
except:
self.router = 'm'
target = example + example
print(example + " -> " + target)
way2 = input(" 确认 取消\n")
if(way2 != '1'):
self.router = 'h'
return 0
for i in selectedIndexList:
k = fileList
self.infoDict = k + k
# 新增
def newFilename(self, info=''):
fileList = self.fileList
selectedIndexList = self.selectedIndexList
# 取例子字符串
example = fileList]
print(self.CreateIndexNumbers(list(example), True))
try:
start = int(input("插入点: \n"))
position = input("在插入点 前 后\n")
info = info or input("插入内容:\n")
if(position == '1'):
target = example + info + example
print(example + " -> " + target)
way2 = input(" 确认 取消\n")
if(way2 != '1'):
self.router = 'm'
return 0
elif(position == '2'):
start = start + 1
target = example + info + example
print(example + " -> " + target)
way2 = input(" 确认 取消\n")
if(way2 != '1'):
self.router = 'm'
return 0
for i in selectedIndexList:
k = fileList
self.infoDict = k + info + k
except:
self.router = 'm'
# 截取
def splitFilename(self):
fileList = self.fileList
selectedIndexList = self.selectedIndexList
# 取例子字符串
example = fileList]
print(self.CreateIndexNumbers(list(example), True))
try:
selected = input("输入位置(起点-终点) :\n")
selected =
start = selected
end = selected + 1
except:
self.router = 'm'
fileSuffix = input("输入文件后缀: \n")
target = example + fileSuffix
print(example + " -> " + target)
way2 = input(" 确认 取消\n")
if(way2 != '1'):
self.router = 'm'
return 0
for i in selectedIndexList:
k = fileList
self.infoDict = k + fileSuffix
# 生成有序序列
def generateFilename(self):
fileList = self.fileList
selectedIndexList = self.selectedIndexList
fileSelectedList = for i in selectedIndexList]
example = fileSelectedList
example2 = fileSelectedList[-1]
try:
startNmber = int(input("请输入起始序号: \n"))
endNmber = startNmber + len(fileSelectedList)
info =
print(self.CreateIndexNumbers(list(example), True))
start = int(input("插入点: \n"))
position = input("在插入点 前 后\n")
if(position == '2'): start = start + 1
target = example + info + example + '...' + example2 + info[-1] + example2
print('(' + example + '...' + example2 + ')' + " -> " + '(' + target + ')')
way2 = input(" 确认 取消\n")
if(way2 != '1'):
self.router = 'm'
return 0
for i in range(len(fileSelectedList)):
k = fileSelectedList
self.infoDict = k + info + k
except:
self.router = 'm'
# -----------------------文件修改方法---------------------------
# 文件重命名
def renameFile(self, oldName:str, newName:str):
oldNamePath = self.originPath + "/" + oldName
newNamePath = self.originPath + "/" + newName
os.rename(oldNamePath, newNamePath)
print(oldName + " -> " + newName)
# 文件批量重命名
def reNameFiles(self, fileList:list, selectedIndex:list):
for i in selectedIndex:
oldname = fileList
newname = self.infoDict]
self.renameFile(oldname,newname)
print("修改完毕!!!")
# -----------------------切片方法---------------------------
# 返回字符串中的中文
@staticmethod
def extractChinese(text:str) ->list:
chinese_pattern = re.compile('[\u4E00-\u9FA5]+')
chinese_text = chinese_pattern.findall(text)
return chinese_text
# 返回字符串中的数字
@staticmethod
def extractNumber(text:str) ->list:
nmber_pattern = re.compile(r'\d+')
nmber_text = nmber_pattern.findall(text)
return nmber_text
# 返回字符串中的字母
@staticmethod
def extractWord(text:str) ->list:
Word_pattern = re.compile(r'+')
Word_text = Word_pattern.findall(text)
return Word_text
# 返回字符串中的文件格式
@staticmethod
def extractFilename(text:str) ->list:
Filename_pattern = re.compile(r'\.{3,4}')
Filename_text = Filename_pattern.findall(text)
return Filename_text
# 返回字符串中的身份证
@staticmethod
def extractID(text:str) ->list:
ID_pattern = re.compile(r'\d{17}[\dXx]')
ID_text = ID_pattern.findall(text)
return ID_text
# 返回字符串中的电话号
@staticmethod
def extractTelephoneNmber(text:str) ->list:
TelephoneNmber_pattern = re.compile(r"1\d{9}")
TelephoneNmber_text = TelephoneNmber_pattern.findall(text)
return TelephoneNmber_text
# 返回依据传入的列表的相应长度的序号+项组合
@staticmethod
def CreateIndexNumbers(list:list, showNeg=False) ->str:
index = ''
listsize = len(list)
size = len(str(listsize))
if(not(showNeg)):
# [序号] + 项
for i in range(len(list)): index = index + '[' + str(i).center(size,' ') + ']' + ' ' + list + '\n'
else:
# [负数序号] + [序号] 项
for i in range(len(list)): index = index + '[' + str(i - len(list)).center(size + 1,' ') + ']' + ' ' + '[' + str(i).center(size,' ') + ']' + list + '\n'
return index
if "__main__" == __name__:
fileBatching1 = fileBatching()
页:
[1]