批量修改文件夹内图片名称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。