鱼C论坛

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

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

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

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

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

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

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

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

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

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

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


                               
登录/注册后可看大图


代码展示:
import os
import re

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

    # 文件列表
    fileList = []

    # 文件索引信息
    selectedIndexList = []

    # 模式选择
    selectMODE = ''

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

    MODE = {}

    ROUTE = {}

    # 路由选择信息
    router = ''
        
    def __init__(self) -> None:
        # 模式信息
        self.MODE = {
            '1':{
                'name':'[1] 原文件名重组',
                'method':self.regroup,
            },
            '2':{
                'name':'[2] 自定义文件名',
                'method':self.userDefined,
            },
        }

        # 路由信息
        self.ROUTE = {
            'h':{
                'MODE':'[h] 主页面',
                # 模式对应的页面
                'PAGE':self.PRINTROUTE,
                # 控制是否显示
                'SHOW':False,
            },            
            's':{
                'MODE':'[s] 选择文件',
                'PAGE':self.SELECTFILE,
                'SHOW':True,
            },
            'm':{
                'MODE':'[m] 选择模式',
                'PAGE':self.PRINTMODE,
                'SHOW':False
            },
            'c': {
                'MODE':'[c] 信息确认修改',
                'PAGE':self.CONFIRM,
                'SHOW':False
            },
            't':{
                'MODE':'[t] 测试页',
                'PAGE':self.TESTPAGE1,
                'SHOW':False
            },
            'e':{
                'MODE':'[e] 结束',
                '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[i]['SHOW']):
                    self.ROUTE[i]['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[self.selectMODE]['name']
        print(file)
        print(mode, "\n")
        for route in self.ROUTE: 
            if(self.ROUTE[route]['SHOW']): print(self.ROUTE[route]['MODE'],end=' ')
        self.router = input("请选择下一步 \n")

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

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

        # 根据模式选择方法 更新infoDict属性
        self.MODE[self.selectMODE]['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("[1] 选择文件 [2] 选择文件夹\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 = [int(i) for i in selected.split(",")]
                self.selectedIndexList = selected
            # 起点-终点 (不能用于负数)
            elif('-' in selected):
                selected = [int(i) for i in selected.split("-")]
                selectedStart = selected[0]
                selectedEnd = selected[1] + 1
                self.selectedIndexList = [i for i in range(selectedStart, selectedEnd)]
            elif(selected == '*'):
                self.selectedIndexList = [i for i in range(len(fileList))]
        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[i])

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

        confirm = input("[1] 确认 [2]取消 \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[selectedIndexList[0]]
        # 取例子
        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 = [int(i) for i in input("请输入规则,例子:   [0]a [1]b [2]c [3]d   规则: 023等于acd, 123等于bcd \n")]
        # 确认修改信息 更新infoDict属性
        for i in selectedIndexList:
            it = fileList[i]
            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[key]
                self.infoDict[fileList[i]] = info
                
    # 自定义 修改重组信息self.infoDict
    def userDefined(self):
        # 操作选项
        way = '1'
        # 初始化infoDict
        self.infoDict = {}

        print("|","确认规则".center(51,"*"),"|")
        
        way = input("选择要进行的操作: [1] 删除  [2] 新增  [3] 截取 [4] 生成有序序列\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[selectedIndexList[0]]
        # 例子+序号
        print(self.CreateIndexNumbers(list(example)))

        try:
            selected = input("输入位置(起点-终点) :\n")
            selected = [int(i) for i in selected.split("-")]
            start = selected[0]
            end = selected[1] + 1
        except:
            self.router = 'm'
                
            
        target = example[0:start] + example[end:len(example)]
        print(example + " -> " + target)

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

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

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

            if(position == '1'):
                target = example[0:start] + info + example[start:len(example)]
                print(example + " -> " + target)
                way2 = input("[1] 确认 [2] 取消\n")
                if(way2 != '1'):
                    self.router = 'm'
                    return 0
                    
            elif(position == '2'):
                start = start + 1
                target = example[0:start] + info + example[start:len(example)]
                print(example + " -> " + target)
                way2 = input("[1] 确认 [2] 取消\n")
                if(way2 != '1'):
                    self.router = 'm'
                    return 0
                
            for i in selectedIndexList:
                k = fileList[i]
                self.infoDict[k] = k[0:start] + info + k[start:len(k)]

        except:
            self.router = 'm'

    # 截取
    def splitFilename(self):
        fileList = self.fileList
        selectedIndexList = self.selectedIndexList
        # 取例子字符串
        example = fileList[selectedIndexList[0]]
        print(self.CreateIndexNumbers(list(example), True))
        try:
            selected = input("输入位置(起点-终点) :\n")
            selected = [int(i) for i in selected.split("-")]
            start = selected[0]
            end = selected[1] + 1
            
        except:
            self.router = 'm'
        
        fileSuffix = input("输入文件后缀: \n")
        target = example[start:end] + fileSuffix
        print(example + " -> " + target)
        way2 = input("[1] 确认 [2] 取消\n")
        if(way2 != '1'):
            self.router = 'm'
            return 0
        
        for i in selectedIndexList:
            k = fileList[i]
            self.infoDict[k] = k[start:end] + fileSuffix

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

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

            target = example[0:start] + info[0] + example[start:len(example)] + '...' + example2[0:start] + info[-1] + example2[start:len(example2)]
            print('(' + example + '...' + example2 + ')' + " -> " + '(' + target + ')')
            way2 = input("[1] 确认 [2] 取消\n")
            if(way2 != '1'):
                self.router = 'm'
                return 0
                
            for i in range(len(fileSelectedList)):
                k = fileSelectedList[i]
                self.infoDict[k] = k[0:start] + info[i] + k[start:len(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[i]
            newname = self.infoDict[fileList[i]]
            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'[A-Za-z]+')
        Word_text = Word_pattern.findall(text)
        return Word_text
    
    # 返回字符串中的文件格式
    @staticmethod
    def extractFilename(text:str) ->list:
        Filename_pattern = re.compile(r'\.[A-Za-z0-9]{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[3456789]\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[i] + '\n'
        else:
            # [负数序号] + [序号] 项
            for i in range(len(list)): index = index + '[' + str(i - len(list)).center(size + 1,' ') + ']' + ' ' + '[' + str(i).center(size,' ') + ']' + list[i] + '\n'
        return index
    


if "__main__" == __name__:
    fileBatching1 = fileBatching()

评分

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

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-8 02:26:55 | 显示全部楼层
:o:o:time:
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-6-28 23:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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