python 遍历指定目录下所有的文件进行文件名的修改

遍历指定目录下所有的文件进行文件名的修改

import os,re

class Ren:

    def __init__(self,file_dir,new_str):

        self.file_dir = file_dir
        self.new_str = new_str


    def file_name(self):
        L = []
        if os.path.exists(self.file_dir):
            for root, dirs, files in os.walk(self.file_dir):
                for file in files:
                    if os.path.splitext(file)[1] == '.success':
                        L.append(os.path.join(root, file))
        else:
            print('文件夹不存在!!')


    def ren_name(self):

        for file in self.file_name():
            try:
                new_str = re.compile('.success')
                str = new_str.sub('', file)
                os.rename(file,str)
                print('%s修改成功!!!'%file)
            except(FileExistsError):
                print('%s文件已存在' %str)
            continue

FILE_DIR = r'd:\1'
FILE_STR = ''

ren = Ren(FILE_DIR,FILE_STR)

ren.ren_name()

 

posted @ 2019-08-07 18:16  yrash2019  阅读(2399)  评论(0编辑  收藏  举报