编程语言
首页 > 编程语言> > python文件批量重命名

python文件批量重命名

作者:互联网

python文件批量重命名

代码如下:

# -*- coding: gbk -*-
import os


class fileRename():
    def __init__(self, path):
        self.__path = path
        self.__order = {}
        self.__files = os.listdir(path)

    def list(self):
        return self.__files

    def presolve(self, string):
        for _ in string.split(";"):
            __ = _.split(",")
            #self.__order.update({__[0]:__[1]})
            self.__order[__[0]] = __[1]
    def rename(self):
        print("当前位于:{}".format(self.__path))
        print("此路径下文件如下:{}".format(self.list()))
        print("请输入想要批量修改的数据(格式为key1,value1;key2,value2;……)")
        self.presolve(input())
        readyToRename = set()
        for o in self.__order.keys():
            for fname in self.__files:
                if o in fname:
                    readyToRename.add(fname)
        print("有 {} 个文件等待修改".format(len(readyToRename)))
        if len(readyToRename) == 0:
            print("Nothing to rename")
            return
        print("是否进行操作? 输入yes/no")
        ans = input()
        if ans == "yes" or ans == "y":
            for f in readyToRename:
                oldname = self.__path +"\\"+ f
                newname = self.__path +"\\"+ f
                for o in self.__order.keys():
                    newname = newname.replace(o,self.__order[o])
                os.rename(oldname,newname)
        elif ans == "no" or ans == "n":
            print("退出")
        else:
            print("指令错误,已退出")
        print("Success!")

f = fileRename(input('请输入文件夹路径'))
f.rename()

标签:重命名,__,.__,python,self,print,path,文件批量,order
来源: https://www.cnblogs.com/Do-n/p/13386124.html