python, tip

Move Jpg, mov, mp4 to somewhere based on the date info

#!/usr/bin/env python
"""
    Move JPG file to dest. directory based on the exif capture date
    and move MOV, mp4 based on the file (modification) date
"""

import os
import sys
import time
import datetime
import shutil
from PIL import Image
from PIL.ExifTags import TAGS

base_dir="."
targetDir = "/Volumes/shared/Photo/2012/"

def getExifInfo(filename, field=""):
    """ Get value for a given tag """
    im = Image.open(filename)
    try:
        info = im._getexif()
    except:
        print "Fail to analyze %s" %filename
        return ""

#   if info == None:
#       print "No EXIF information"
#       return ""

    for key, value in info.items() :
        if field:
            if field == TAGS.get(key, key):
                break;
        else:
            print "  * %-30s %s" %(TAGS.get(key, key) , repr(value))

    try:
        tmp = value.split()[0].split(':')
        return "%s-%s-%s" %(tmp[0], tmp[1], tmp[2])
    except:
        return ""

def main(from_here):
    """ """
    for t in os.walk(from_here):
        for f in t[2]:
            filename = "/".join((t[0], f))

            if filename.endswith("JPG") or filename.endswith("jpg"):
                dateDir = getExifInfo(filename, "DateTimeOriginal")
                if dateDir != "":
                    if not os.path.exists(targetDir+dateDir):
                        os.mkdir(targetDir+dateDir)

                    print "Copy %s => %s" %(filename, targetDir+dateDir)
                    shutil.copy(filename, targetDir+dateDir)

            elif filename.endswith("MOV") or filename.endswith("mp4") or filename.endswith("m4v"):
                tmp = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
                dateDir = str(tmp)[0:10]

                if not os.path.exists(targetDir+dateDir):
                    os.mkdir(targetDir+dateDir)

                print "Copy %s => %s" %(filename, targetDir+dateDir)
                shutil.copy(filename, targetDir+dateDir)

#           elif filename.endswith("PNG") or filename.endswith("png"):
#               print "png", filename
#               print getExifInfo(filename, "DateTimeOriginal")


if __name__ == '__main__':
    if len(sys.argv) > 1:
        if os.path.exists(sys.argv[1]):
            base_dir = sys.argv[1]

    main(base_dir)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s