#!-*- coding: cp936 -*-"
import os
import time
import stat
import re
import sys
import Image
def extract_jpeg_exif_time(jpegfn):
"""
取相片的拍照日期,从网上获取的代码
"""
if not os.path.isfile(jpegfn):
return None
try:
im = Image.open(jpegfn)
if hasattr(im, '_getexif'):
exifdata = im._getexif()
ctime = exifdata[0x9003]
return ctime
except:
pass
# _type, value, traceback = sys.exc_info()
# print "Error:\n%s", jpegfn
return None
def get_exif_prefix(jpegfn):
"""
按一定格式返回日期,从网上获取的代码
"""
ctime = extract_jpeg_exif_time(jpegfn)
if ctime is None:
return None
ctime = ctime.replace(':', '')
ctime = re.sub('[^\d]+', '_', ctime)
ctime = ctime[:ctime.find('_')]
return ctime
def ctime(creationtime):
"""CreationTime时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),
返回时间字符串
"""
return time.strftime('%Y%m%d',time.localtime(creationtime))
def mktime(date):
"""
返回时间戳,date是字符型日期
"""
d1 = re.sub('[ -\.:]', '', date)
return time.mktime(time.strptime(d1,'%Y%m%d'))
def howmonth(date1,date2):
"""date1,date2是时间戳,
返回两个时间戳的间隔月数
"""
return str(int((date2-date1)/(30*24*60*60)))
def renamefile(Spath,Dpath,Birthday):
"""把Spath源目录的文件改名为P_出生天数_照相时间_顺序数到Dpath目标目录"""
nfile=''
if not os.path.exists(Spath):
print Spath,"此目录不存在,请重新指定!"
return
if not os.path.exists(Dpath):
os.mkdir(Dpath)
for dirpath,dirnames,filenames in os.walk(Spath):
i=0
for files in filenames:
sfile=os.path.join(dirpath,files)
fileStats=os.stat(sfile)
createtime=fileStats[stat.ST_MTIME]
birtime=mktime(Birthday)
ptime=get_exif_prefix(sfile)
if ptime:
createtime=mktime(ptime)
months=howmonth(birtime,createtime)
phonetime=ctime(createtime)
(file,ext)=os.path.splitext(files)
nfile='P_'+months+'_'+phonetime+'_'+str(i)+ext
nfile= os.path.join(Dpath,nfile)
while os.path.exists(nfile):
i+=1
nfile='P_'+months+'_'+phonetime+'_'+str(i)+ext
nfile= os.path.join(Dpath,nfile)
try:
os.rename(sfile,nfile)
except os.error,e:
print e,sfile,'to',nfile
def usage():
print """
修改文件名为P_拍照日期与指定日期的间隔月份_拍照日期_重复顺序数.后缀
使用方法:
imgfilerename spath dpath birthday
"""
if __name__=="__main__":
if len(sys.argv)<>4:
usage()
sys.exit(2)
renamefile(sys.argv[1],sys.argv[2],sys.argv[3])
print 'rename all file,ok!'
评论0