Automatically renaming image files

I’ve given up on trying to find a good naming scheme for my digital photos. It’s just too much work. So now I just run a small Python script that parses the Exif info, extracts the time stamp the photo was taken, and renames the image file to yyyy_mm_dd_hhmmss.JPG. Then I just sort the files into a separate folder for each month and I’m done. The probability of two images taken at the same second is reasonably low not to run into naming conflicts.

Not exactly a life-saver, but nevertheless quite a handy script:

#!/usr/bin/python

from PIL import Image
from PIL.ExifTags import TAGS
import os
import sys

def getImageDate(fn):
    info = Image.open(fn)._getexif()
    dt = ""
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        print "%s => %s" % (decoded, value)
        if decoded == "DateTimeOriginal": return value
        if decoded == "DateTimeDigitized": return value
        if decoded == "DateTime": dt = value
    if dt != "": return dt
    return 0

for fn in sys.argv[1:]:
    try:
        path = os.path.dirname(fn)
        dt = getImageDate(fn).replace(" ", "_").replace(":", "_", 2).replace(":", "") + ".JPG"
        dest = os.path.join(path, dt)
        if dt.startswith("0000_00"):
            print "Skipping %s" % (fn)
        else:
            if os.path.exists(dest):
                print "Dest file exists, skipping %s" % (dest)
            else:
                os.rename(fn, dest)
                print "%s -> %s" % (fn, dest)
    except:
        print "Skipping %s" % (fn)

Advertisements

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