鱼C论坛

 找回密码
 立即注册
查看: 1834|回复: 1

[作品展示] 文件批量重命名工具(小黑框)!!!

[复制链接]
发表于 2023-10-25 18:57:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
新手发帖,不规范的地方有很多,各路大佬手下留情

功能介绍:
一、文件名重组
分离出原文件名的汉字、数字、字母、文件格式、手机号、身份证号手动选择重新组合

二、 自定义文件名(固定位置修改)
1.删除
手动选择固定位置,删除固定位置的文件名

2.新增
在原文件名指定位置插入新增文件名

3.截取
截取并保留原文件名固定位置的文件名

4.生成有序序列
在原文件名指定位置插入从指定数开始的有序序列


                               
登录/注册后可看大图


代码展示:
  1. import os
  2. import re

  3. class fileBatching():
  4.     # 目标文件夹路径
  5.     originPath = ''

  6.     # 文件列表
  7.     fileList = []

  8.     # 文件索引信息
  9.     selectedIndexList = []

  10.     # 模式选择
  11.     selectMODE = ''

  12.     # 文件名修改信息 原文件名:新文件名
  13.     # 所有操作都是先修改infoDict属性 最后通过infoDict修改文件名
  14.     infoDict = {}

  15.     MODE = {}

  16.     ROUTE = {}

  17.     # 路由选择信息
  18.     router = ''
  19.         
  20.     def __init__(self) -> None:
  21.         # 模式信息
  22.         self.MODE = {
  23.             '1':{
  24.                 'name':'[1] 原文件名重组',
  25.                 'method':self.regroup,
  26.             },
  27.             '2':{
  28.                 'name':'[2] 自定义文件名',
  29.                 'method':self.userDefined,
  30.             },
  31.         }

  32.         # 路由信息
  33.         self.ROUTE = {
  34.             'h':{
  35.                 'MODE':'[h] 主页面',
  36.                 # 模式对应的页面
  37.                 'PAGE':self.PRINTROUTE,
  38.                 # 控制是否显示
  39.                 'SHOW':False,
  40.             },            
  41.             's':{
  42.                 'MODE':'[s] 选择文件',
  43.                 'PAGE':self.SELECTFILE,
  44.                 'SHOW':True,
  45.             },
  46.             'm':{
  47.                 'MODE':'[m] 选择模式',
  48.                 'PAGE':self.PRINTMODE,
  49.                 'SHOW':False
  50.             },
  51.             'c': {
  52.                 'MODE':'[c] 信息确认修改',
  53.                 'PAGE':self.CONFIRM,
  54.                 'SHOW':False
  55.             },
  56.             't':{
  57.                 'MODE':'[t] 测试页',
  58.                 'PAGE':self.TESTPAGE1,
  59.                 'SHOW':False
  60.             },
  61.             'e':{
  62.                 'MODE':'[e] 结束',
  63.                 'PAGE':lambda : 0,
  64.                 'SHOW':True
  65.             },
  66.         }

  67.         # 路由选择
  68.         self.router = 'h'

  69.     # 监听路由
  70.     @property
  71.     def router(self,route):
  72.         return route

  73.     # 监听路由
  74.     @router.setter
  75.     def router(self, route):
  76.         # h是路由选择页面 但不显示选项
  77.         if(route == 'h'):
  78.             self.ROUTE['h']['PAGE']()
  79.         else:
  80.             # 选哪个选项 调用哪个选项的页面
  81.             for i in self.ROUTE:
  82.                 if(route == i and self.ROUTE[i]['SHOW']):
  83.                     self.ROUTE[i]['PAGE']()
  84.       
  85.     # -----------------------页面---------------------------

  86.     # 测试页1 测试添加页面
  87.     def TESTPAGE1(self):
  88.         print("|","测试页".center(51,"*"),"|\n")
  89.         self.router = 'h'

  90.     # 路由选项页面
  91.     def PRINTROUTE(self):
  92.         print("|","文件批量重命名工具".center(51,"*"),"|\n")
  93.         file = "文件夹: " + "未选择" if self.originPath == ''else "文件夹: " + self.originPath
  94.         mode = "模式: " + "未选择" if self.selectMODE == '' else "模式: " + self.MODE[self.selectMODE]['name']
  95.         print(file)
  96.         print(mode, "\n")
  97.         for route in self.ROUTE:
  98.             if(self.ROUTE[route]['SHOW']): print(self.ROUTE[route]['MODE'],end=' ')
  99.         self.router = input("请选择下一步 \n")

  100.     # 重命名模式选项页面
  101.     def PRINTMODE(self):
  102.         print("|","选择重命名模式".center(51,"*"),"|")
  103.         # 打印所有模式选项
  104.         for mode in self.MODE: print(self.MODE[mode]['name'])

  105.         self.selectMODE = input("选择修改模式: \n")
  106.         
  107.         # 乱输就重新输
  108.         try:self.MODE[self.selectMODE]
  109.         except:self.router = 'h'

  110.         # 根据模式选择方法 更新infoDict属性
  111.         self.MODE[self.selectMODE]['method']()
  112.         # 打开确认修改界面显示
  113.         self.ROUTE['c']['SHOW'] = True         
  114.         # 路由
  115.         self.router = 'h'

  116.     # 文件选项页面 并设置需要重命名的文件索引
  117.     def SELECTFILE(self):
  118.         # 乱输就重新输
  119.         try:
  120.             if(self.originPath == ''):
  121.                 self.originPath = input("选择文件夹路径(把文件夹拉进来或复制绝对路径 首尾不要带双引号!):\n")
  122.                 fileList = self.fileList = os.listdir(self.originPath)
  123.             else:
  124.                 otherFile = input("[1] 选择文件 [2] 选择文件夹\n")
  125.                 if(otherFile == '1'):
  126.                     fileList = self.fileList = os.listdir(self.originPath)

  127.                 elif(otherFile == '2'):
  128.                     self.originPath = input("选择文件夹路径(把文件夹拉进来!):\n")
  129.                     fileList = self.fileList = os.listdir(self.originPath)

  130.             print("|","选择文件".center(51,"*"),"|")

  131.             # 序号文件名组合
  132.             fileListAndIndex = self.CreateIndexNumbers(fileList)
  133.             print(fileListAndIndex)
  134.             selected = input("请选择需要重命名的文件以英文逗号( , )隔开 星号( * )代表全选: \n")
  135.             if(',' in selected):
  136.                 selected = [int(i) for i in selected.split(",")]
  137.                 self.selectedIndexList = selected
  138.             # 起点-终点 (不能用于负数)
  139.             elif('-' in selected):
  140.                 selected = [int(i) for i in selected.split("-")]
  141.                 selectedStart = selected[0]
  142.                 selectedEnd = selected[1] + 1
  143.                 self.selectedIndexList = [i for i in range(selectedStart, selectedEnd)]
  144.             elif(selected == '*'):
  145.                 self.selectedIndexList = [i for i in range(len(fileList))]
  146.         except:
  147.             self.router = 's'

  148.         # 模式选项打开
  149.         self.ROUTE['m']['SHOW'] = True

  150.         # 路由
  151.         self.router = 'h'
  152.    
  153.     # 确认页面
  154.     def CONFIRM(self):
  155.         # 打印选中的文件
  156.         fileList = self.fileList
  157.         selectfileList = []
  158.         for i in self.selectedIndexList:
  159.             selectfileList.append(fileList[i])

  160.         print("|","确认修改信息".center(51,"*"),"|")
  161.         
  162.         for i in self.infoDict:
  163.             print(i + ' -> ' + self.infoDict[i])

  164.         confirm = input("[1] 确认 [2]取消 \n")
  165.         if(confirm == '1'):
  166.             self.reNameFiles(fileList, self.selectedIndexList)
  167.         else:
  168.             self.router = 'h'
  169.             return 0

  170.         self.ROUTE['c']['SHOW'] = False
  171.         self.ROUTE['m']['SHOW'] = False
  172.         # 路由
  173.         self.router = 'h'
  174.    
  175.     # -----------------------组件---------------------------

  176.     # 重组 修改重组信息self.infoDict
  177.     def regroup(self):
  178.         rulesList = []
  179.         self.infoDict = {}
  180.         fileList = self.fileList
  181.         selectedIndexList = self.selectedIndexList
  182.         example = fileList[selectedIndexList[0]]
  183.         # 取例子
  184.         rulesList = rulesList + self.extractChinese(example) + self.extractNumber(example) + self.extractWord(example) + self.extractFilename(example) + self.extractID(example) + self.extractTelephoneNmber(example)

  185.         print("|","确认规则".center(51,"*"),"|")

  186.         # 打印序号选择列表
  187.         print(self.CreateIndexNumbers(rulesList))
  188.         # 生成规则 覆盖rulesList
  189.         rulesList = [int(i) for i in input("请输入规则,例子:   [0]a [1]b [2]c [3]d   规则: 023等于acd, 123等于bcd \n")]
  190.         # 确认修改信息 更新infoDict属性
  191.         for i in selectedIndexList:
  192.             it = fileList[i]
  193.             info = ''
  194.             k = self.extractChinese(it) + self.extractNumber(it) + self.extractWord(it) + self.extractFilename(it) + self.extractID(it) + self.extractTelephoneNmber(it)
  195.             for key in rulesList:
  196.                 info = info + k[key]
  197.                 self.infoDict[fileList[i]] = info
  198.                
  199.     # 自定义 修改重组信息self.infoDict
  200.     def userDefined(self):
  201.         # 操作选项
  202.         way = '1'
  203.         # 初始化infoDict
  204.         self.infoDict = {}

  205.         print("|","确认规则".center(51,"*"),"|")
  206.         
  207.         way = input("选择要进行的操作: [1] 删除  [2] 新增  [3] 截取 [4] 生成有序序列\n")

  208.         # 删除
  209.         if(way == '1'):
  210.             self.delFilename()

  211.         # 新增
  212.         elif(way == '2'):
  213.             self.newFilename()
  214.                
  215.             
  216.         # 截取
  217.         elif(way == '3'):
  218.             self.splitFilename()

  219.         # 生成序列
  220.         elif(way == '4'):
  221.             self.generateFilename()

  222.         else:
  223.             # 乱输就回去吧你
  224.             self.router = 'h'

  225.     # 删除
  226.     def delFilename(self):
  227.         fileList = self.fileList
  228.         selectedIndexList = self.selectedIndexList
  229.         # 取例子字符串
  230.         example = fileList[selectedIndexList[0]]
  231.         # 例子+序号
  232.         print(self.CreateIndexNumbers(list(example)))

  233.         try:
  234.             selected = input("输入位置(起点-终点) :\n")
  235.             selected = [int(i) for i in selected.split("-")]
  236.             start = selected[0]
  237.             end = selected[1] + 1
  238.         except:
  239.             self.router = 'm'
  240.                
  241.             
  242.         target = example[0:start] + example[end:len(example)]
  243.         print(example + " -> " + target)

  244.         way2 = input("[1] 确认 [2] 取消\n")
  245.         if(way2 != '1'):
  246.             self.router = 'h'
  247.             return 0
  248.         
  249.         for i in selectedIndexList:
  250.             k = fileList[i]
  251.             self.infoDict[k] = k[0:start] + k[end:len(k)]

  252.     # 新增
  253.     def newFilename(self, info=''):
  254.         fileList = self.fileList
  255.         selectedIndexList = self.selectedIndexList
  256.         # 取例子字符串
  257.         example = fileList[selectedIndexList[0]]
  258.         print(self.CreateIndexNumbers(list(example), True))
  259.         try:
  260.             start = int(input("插入点: \n"))
  261.             position = input("在插入点  [1] 前 [2] 后\n")

  262.             info = info or input("插入内容:\n")

  263.             if(position == '1'):
  264.                 target = example[0:start] + info + example[start:len(example)]
  265.                 print(example + " -> " + target)
  266.                 way2 = input("[1] 确认 [2] 取消\n")
  267.                 if(way2 != '1'):
  268.                     self.router = 'm'
  269.                     return 0
  270.                     
  271.             elif(position == '2'):
  272.                 start = start + 1
  273.                 target = example[0:start] + info + example[start:len(example)]
  274.                 print(example + " -> " + target)
  275.                 way2 = input("[1] 确认 [2] 取消\n")
  276.                 if(way2 != '1'):
  277.                     self.router = 'm'
  278.                     return 0
  279.                
  280.             for i in selectedIndexList:
  281.                 k = fileList[i]
  282.                 self.infoDict[k] = k[0:start] + info + k[start:len(k)]

  283.         except:
  284.             self.router = 'm'

  285.     # 截取
  286.     def splitFilename(self):
  287.         fileList = self.fileList
  288.         selectedIndexList = self.selectedIndexList
  289.         # 取例子字符串
  290.         example = fileList[selectedIndexList[0]]
  291.         print(self.CreateIndexNumbers(list(example), True))
  292.         try:
  293.             selected = input("输入位置(起点-终点) :\n")
  294.             selected = [int(i) for i in selected.split("-")]
  295.             start = selected[0]
  296.             end = selected[1] + 1
  297.             
  298.         except:
  299.             self.router = 'm'
  300.         
  301.         fileSuffix = input("输入文件后缀: \n")
  302.         target = example[start:end] + fileSuffix
  303.         print(example + " -> " + target)
  304.         way2 = input("[1] 确认 [2] 取消\n")
  305.         if(way2 != '1'):
  306.             self.router = 'm'
  307.             return 0
  308.         
  309.         for i in selectedIndexList:
  310.             k = fileList[i]
  311.             self.infoDict[k] = k[start:end] + fileSuffix

  312.     # 生成有序序列
  313.     def generateFilename(self):
  314.         fileList = self.fileList
  315.         selectedIndexList = self.selectedIndexList
  316.         fileSelectedList = [fileList[i] for i in selectedIndexList]
  317.         example = fileSelectedList[0]
  318.         example2 = fileSelectedList[-1]
  319.         try:
  320.             startNmber = int(input("请输入起始序号: \n"))
  321.             endNmber = startNmber + len(fileSelectedList)
  322.             info = [str(i) for i in range(startNmber, endNmber)]
  323.             print(self.CreateIndexNumbers(list(example), True))
  324.             start = int(input("插入点: \n"))
  325.             position = input("在插入点  [1] 前 [2] 后\n")

  326.             if(position == '2'): start = start + 1

  327.             target = example[0:start] + info[0] + example[start:len(example)] + '...' + example2[0:start] + info[-1] + example2[start:len(example2)]
  328.             print('(' + example + '...' + example2 + ')' + " -> " + '(' + target + ')')
  329.             way2 = input("[1] 确认 [2] 取消\n")
  330.             if(way2 != '1'):
  331.                 self.router = 'm'
  332.                 return 0
  333.                
  334.             for i in range(len(fileSelectedList)):
  335.                 k = fileSelectedList[i]
  336.                 self.infoDict[k] = k[0:start] + info[i] + k[start:len(k)]

  337.             
  338.         except:
  339.             self.router = 'm'


  340.     # -----------------------文件修改方法---------------------------

  341.     # 文件重命名
  342.     def renameFile(self, oldName:str, newName:str):
  343.         oldNamePath = self.originPath + "/" + oldName
  344.         newNamePath = self.originPath + "/" + newName
  345.         os.rename(oldNamePath, newNamePath)
  346.         print(oldName + " -> " + newName)

  347.     # 文件批量重命名
  348.     def reNameFiles(self, fileList:list, selectedIndex:list):
  349.         for i in selectedIndex:
  350.             oldname = fileList[i]
  351.             newname = self.infoDict[fileList[i]]
  352.             self.renameFile(oldname,newname)
  353.             
  354.         print("修改完毕!!!")

  355.     # -----------------------切片方法---------------------------

  356.     # 返回字符串中的中文
  357.     @staticmethod
  358.     def extractChinese(text:str) ->list:
  359.         chinese_pattern = re.compile('[\u4E00-\u9FA5]+')
  360.         chinese_text = chinese_pattern.findall(text)
  361.         return chinese_text

  362.     # 返回字符串中的数字
  363.     @staticmethod
  364.     def extractNumber(text:str) ->list:
  365.         nmber_pattern = re.compile(r'\d+')
  366.         nmber_text = nmber_pattern.findall(text)
  367.         return nmber_text
  368.    
  369.     # 返回字符串中的字母
  370.     @staticmethod
  371.     def extractWord(text:str) ->list:
  372.         Word_pattern = re.compile(r'[A-Za-z]+')
  373.         Word_text = Word_pattern.findall(text)
  374.         return Word_text
  375.    
  376.     # 返回字符串中的文件格式
  377.     @staticmethod
  378.     def extractFilename(text:str) ->list:
  379.         Filename_pattern = re.compile(r'\.[A-Za-z0-9]{3,4}')
  380.         Filename_text = Filename_pattern.findall(text)
  381.         return Filename_text

  382.     # 返回字符串中的身份证
  383.     @staticmethod
  384.     def extractID(text:str) ->list:
  385.         ID_pattern = re.compile(r'\d{17}[\dXx]')
  386.         ID_text = ID_pattern.findall(text)
  387.         return ID_text

  388.     # 返回字符串中的电话号
  389.     @staticmethod
  390.     def extractTelephoneNmber(text:str) ->list:
  391.         TelephoneNmber_pattern = re.compile(r"1[3456789]\d{9}")
  392.         TelephoneNmber_text = TelephoneNmber_pattern.findall(text)
  393.         return TelephoneNmber_text
  394.    
  395.     # 返回依据传入的列表的相应长度的序号+项组合
  396.     @staticmethod
  397.     def CreateIndexNumbers(list:list, showNeg=False) ->str:
  398.         index = ''
  399.         listsize = len(list)
  400.         size = len(str(listsize))
  401.         if(not(showNeg)):
  402.             # [序号] + 项
  403.             for i in range(len(list)): index = index + '[' + str(i).center(size,' ') + ']' + ' ' + list[i] + '\n'
  404.         else:
  405.             # [负数序号] + [序号] 项
  406.             for i in range(len(list)): index = index + '[' + str(i - len(list)).center(size + 1,' ') + ']' + ' ' + '[' + str(i).center(size,' ') + ']' + list[i] + '\n'
  407.         return index
  408.    


  409. if "__main__" == __name__:
  410.     fileBatching1 = fileBatching()

复制代码

评分

参与人数 2荣誉 +10 贡献 +6 收起 理由
python爱好者. + 5 + 3 鱼C有你更精彩^_^
歌者文明清理员 + 5 + 3

查看全部评分

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2023-11-8 02:26:55 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 12:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表