#!/usr/bin/env python
'''
A simple Python script to sort image files into different directories
according to its EXIF tags.
lestercheung AT gmail.com
'''
import os, sys
import datetime
if '__file__' in dir(): # Put EXIF.py on the same directory
sys.path.append(os.path.dirname(__file__))
import EXIF
from exceptions import Exception
def getctime(filename):
dt = datetime.datetime.fromtimestamp(os.stat(filename).st_ctime)
try:
tags = EXIF.process_file(file(filename, 'rb'))
dtstr = tags.get('EXIF DateTimeOriginal').printable
subsecstr = tags.get('EXIF SubSecTimeOriginal').printable
usec = 0 # microsecond portion of timestamp
for i in range(len(subsecstr)):
if 5-i < 1:
break
j = subsecstr[i]
usec += int(j) * 10**(5-i)
if dtstr:
dt = datetime.datetime.strptime(dtstr+str(usec), '%Y:%m:%d %H:%M:%S%f')
except Exception, e:
sys.stderr.write('error parsing date tag, using file timestamp for %s' % filename)
sys.stderr.write(str(e))
sys.stderr.write('\n')
return dt
def getdstfname(src, dstdir=''):
dt = getctime(src)
ext = os.path.basename(src)
x = src.split('.')
if len(x) > 1:
ext = x[-1]
# fname = dt.strftime('%Y%m%d_%H%M%S%f')
fname = os.path.basename(src)
pathname = os.path.join(dstdir, str(dt.year), dt.strftime('%m'), dt.strftime('%d'), fname)
if os.path.exists(pathname):
i = 1
while os.path.exists(pathname):
pathname = os.path.join(dstdir, str(dt.year), dt.strftime('%m'), dt.strftime('%d'), fname.split()[0]+'-%03d.'%i+ext)
i+=1
return pathname
def link_or_copy(src, dst):
print "link_or_copy(%s, %s)" % (src, dst)
if os.path.exists(dst):
print '%s exists! Aborting' % dst
return
dstdir = os.path.dirname(dst)
if not os.path.exists(dstdir):
os.makedirs(dstdir)
try:
os.link(src, dst)
except OSError, e: # copy and reset timestamp
fd = file(dst, 'w')
fd.write(file(src).read())
fd.close()
ctime = getctime(dst)
from time import mktime
# this is not precise - see: http://bugs.python.org/issue2736
atime = mtime = mktime(ctime.timetuple()) # setting all to DateTimeOriginal
os.utime(dst, (atime, mtime))
if __name__ == '__main__':
srcdir, dstdir = sys.argv[1:3]
failed_files = []
copied = 0
for base, dirs, files in os.walk(srcdir):
for f in files:
ff = os.path.join(base,f)
#print ff
from exceptions import Exception, OSError
try:
link_or_copy(ff, getdstfname(ff, dstdir=dstdir))
copied += 1
except OSError, e:
failed_files.append(ff)
except Exception, e:
raise
if failed_files:
print 'failed to link/copy %s files:\n' % len(failed_files)
for i in failed_files:
print ' %s' % i
print 'copied %s files.' % copied
Thursday, March 18, 2010
Sorting photos from your digital camera
Labels:
python photo script
| Reactions: |
Wednesday, March 10, 2010
Slow startup for Dictionary.app on MacOSX
... fixed by removing the following 2 directories: ~/Library/Caches/com.apple.DictionaryApp ~/Library/Caches/com.apple.DictionaryServices.
Subscribe to:
Posts (Atom)