修改图片的MIME类型及使其名称排序的脚本

correctMIMEType模块:


import os,sys,shelve,time

def correctMIMEType():
	moduleFileName='correctMIMEType.py'
	fileTypeFile='fileType'
	mimeTypeFile='mime'
	countFile='.fileInfo'
	if not os.path.exists(countFile):
		f=shelve.open(countFile)
		f['count']=0
		f['lastModifiedTime']=0
		f.close()
	for dn in sys.path:
		if os.path.exists(os.path.join(dn,moduleFileName)):
			dirname=dn
			break
	files=[x for x in os.listdir() if os.path.isfile(x)]
	files.sort()
	unknownType=[]
	length=len(files)
	fileType=shelve.open(os.path.join(dirname,fileTypeFile))
	mimeType=shelve.open(os.path.join(dirname,mimeTypeFile))
	curCountFile=shelve.open(countFile)
	curCount=curCountFile['count']
	lastModifiedTime=curCountFile['lastModifiedTime']
	for filename in files:
		if filename[0]!='.':
			if os.path.getatime(filename)<=lastModifiedTime:
				continue
			if os.path.getatime(filename)<=lastModifiedTime:
				continue
			fe=list(os.path.splitext(filename))
			curCount+=1
			fe[0]=str(curCount)
			f=open(filename,'rb').read()
			for pictureType in fileType['pictureType']:
				findType=False
				for tp in mimeType[pictureType]:
					if f[tp[0]:tp[1]]==tp[2]:
						if fe[1]!=pictureType:
							fe[1]=pictureType
						findType=True
						break
				if findType:
					break
			else:
				unknownType.append(filename)
			newname=fe[0]+fe[1]
			if os.path.exists(newname) and newname!=filename:
				newnewname=newname
				ext=list(os.path.splitext(newnewname))
				while(os.path.exists(newnewname)):
					ext[0]=ext[0]+'o'
					newnewname=ext[0]+ext[1]
				files.remove(newname)
				files.append(newnewname)
				os.rename(newname,newnewname)
			os.rename(filename,newname)
	curCountFile['count']=curCount
	curCountFile['lastModifiedTime']=time.time()
	fileType.close()
	mimeType.close()
	curCountFile.close()
	return unknownType


def rearrangeName():
	if not os.path.exists('.fileInfo'):
		correctMIMEType()
	files=[x for x in os.listdir() if os.path.isfile(x) and x[0]!='.']
	fileExt={}
	for x in files:
		try:
			ext=os.path.splitext(x)
			fileExt[int(ext[0])]=ext[1]
		except ValueError:
			ext=os.path.split(x)
			unrelativeNames[ext[0]]=ext[1]
	beforeName=list(fileExt.keys())
	beforeName.sort()
	count=len(beforeName)
	for i in range(count):
		if beforeName[i]==i+1:
			pass
		else:
			last=beforeName.pop()
			beforeName.insert(i,i+1)
			oldname=str(last)+fileExt[last]
			newname=str(i+1)+fileExt[last]
			os.rename(oldname,newname)
	f=shelve.open('.fileInfo')
	f['count']=len(files)
	f['lastModifiedTime']=time.time()
	f.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值