Python开发练习--Python 批量修改文件夹内图片名称demo1

批量修改文件夹内图片名称demo1

批量自动修改图片名称(其实也不限于图片文件。结合其他库,文件命名也可以很有趣—>时间、地点、当时天气…)。

默认根据格式文件创建时间的先后顺序修改当前程序所在文件夹所有图片文件。

默认命名规则为“Img_年-月-日 时-分-秒_序号”,文件命名头可改。

import os
import time

class renamepic():
    '''
    批量自动修改图片名称(其实也不限于图片文件。​结合其他库,文件命名也可以很有趣--->时间、地点、当时天气......)。
    默认根据<jpg png>格式文件创建时间的先后顺序修改当前程序所在文件夹所有图片文件。
    默认命名规则为“Img_年-月-日 时-分-秒_序号”,文件命名头可改。
    '''
    def __init__ (self,path='',beginword='Img_'):
        self.path0=path
        self.beginword=beginword
        
    def renamefile(self):
        if not os.path.exists(self.path0):
            self.path0=os.getcwd()
        
        beginerror='\/:*?"<>|'
        for checkbegin in beginerror:
            if checkbegin in self.beginword:
                return None
        
        os.chdir(self.path0)
        filelist=os.listdir(self.path0)
        piclist=[]
        for filetp in filelist:
            if os.path.isfile(filetp):
                if os.path.splitext(filetp)[-1] in ['.jpg','.png']:
                    dictp={}
                    dictp['path']=filetp
                    dictp['time']=os.path.getctime(filetp)
                    dictp['time1']=time.strftime('%Y%m%d%H%M%S',time.localtime(dictp['time']))
                    dictp['type']=os.path.splitext(filetp)[-1]
                    piclist.append(dictp)

        picdata=[]
        if piclist:
            picdata=sorted(piclist,key=lambda piclist:piclist['time'],reverse=False)
            timelist=[]
            for pictp in picdata:
                timetp=int(str(pictp['time1']))
                timelist.append(timetp)
            timelist=set(timelist)
            for timeset in timelist:
                count=0
                for pictp in picdata:
                    if timeset==int(str(pictp['time1'])):
                        count=count+1
                        pictp['count']=count
            for pictp in picdata:
                newname=self.beginword+str(time.strftime('%Y-%m-%d %H-%M-%S',time.localtime(pictp['time'])))+\
                         '_'+str(pictp['count'])+pictp['type']
                os.rename(pictp['path'],newname)
            return True
        else:
            return None
        
aa=renamepic(path=r"D:\Python\testfile\pic\rename",beginword='Img_')
print(aa.renamefile())

关注Python开发练习,200G学习资源免费送,还可以免费处理2.5小时以内的各类小Task。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值