python实现文件重命名并编号

root_path下有多级文件夹,其中不同文件夹下有同名文件,该脚本可以实现将多级文件夹下的文件重新编号保存到root_path目录下。

# -*- coding:utf-8 -*-

import os


def getFiles(path, suffix):
    return [os.path.join(root, file) for root, dirs, files in os.walk(path) for file in files if file.endswith(suffix)]


class Rename():
    def __init__(self, path, suffix):
        self.path = path
        self.suffix = suffix

    def rename(self):
        filelist = getFiles(self.path, self.suffix)
        total_num = len(filelist)
        i = 0
        for item in filelist:
            if item.endswith(self.suffix):
                src = os.path.join(os.path.abspath(self.path), item)
                dst = os.path.join(os.path.abspath(self.path), format(str(i), '0>6s') + self.suffix)
                os.rename(src, dst)
                print('converting %s to %s ...' % (src, dst))
                i = i + 1
        print('total %d to rename & converted %d jpgs' % (total_num, i))


if __name__ == '__main__':
    root_path = r'D:\dataset\img'
    suffix = '.jpg'
    newname = Rename(root_path, suffix)
    newname.rename()

 

 

 

上一篇:yii访问规则定义为配置数组


下一篇:php-文件系统