Python renames files/pictures in the order of generation (starting from the specified number)

Applicable scenario: The names of files/pictures generated according to time/number are random, and need to be renamed from the specified number in the order of generation, and saved in the original folder:

import os

class BatchRename():

    def __init__(self):
        self.path = '要读取的文件夹地址+/'

    def rename(self):
        filelist = os.listdir(self.path)
        filelist.sort()
        total_num = len(filelist)
        i = 0
        for item in filelist:
            if item.endswith('.png'):#要识别的文件格式尾缀
                src = os.path.join(os.path.abspath(self.path), item)
                s = str(i)
                s = s.zfill(6)
                dst = os.path.join(os.path.abspath(self.path), s + '.png')

                try:
                    os.rename(src, dst)
                    print ('converting %s to %s ...' % (src, dst))
                    i = i + 1
                except:
                    continue
        print ('total %d to rename & converted %d pngs' % (total_num, i))


if __name__ == '__main__':
    demo = BatchRename()
    demo.rename()

Applicable scenario: The names of files/pictures generated by time/numbers are messy, and need to be renamed from special characters + specified numbers in the order of generation, and saved in other folders:

import os
 
class BatchRename():
    '''
    批量重命名文件夹中的图片文件
    '''
    def __init__(self):
        self.path = '要读取的文件夹地址+/'  #表示需要命名处理的文件夹
        self.save_path='要写入的文件夹地址+/'#保存重命名后的图片地址
    def rename(self):
        filelist = os.listdir(self.path) #获取文件路径
        total_num = len(filelist) #获取文件长度(个数)
        i = 200000 #表示文件的命名是从200000开始的
        for item in filelist:
            print(item)
            if item.endswith('.jpg'):  #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
                src = os.path.join(os.path.abspath(self.path), item)#当前文件中图片的地址
                dst = os.path.join(os.path.abspath(self.save_path), '需要添加的其他命名前缀'+ str(i) +  '.jpg')#处理后文件的地址和名称,可以自己按照自己的要求改进
                try:
                    os.rename(src, dst)
                    print ('converting %s to %s ...' % (src, dst))
                    i = i + 1
                except:
                    continue
        print ('total %d to rename & converted %d jpgs' % (total_num, i))
 
if __name__ == '__main__':
    demo = BatchRename()
    demo.rename()

Guess you like

Origin blog.csdn.net/ZHUO__zhuo/article/details/124635151