Skip to content

Instantly share code, notes, and snippets.

@kdmurray
Created May 17, 2015 06:26
Show Gist options
  • Save kdmurray/ef6431cecfff5ed59971 to your computer and use it in GitHub Desktop.
Save kdmurray/ef6431cecfff5ed59971 to your computer and use it in GitHub Desktop.
Photo management script to move folders from a generic import location to a hierarchical set of folders organized by year and month.This script was originally written by Dr. Drang: http://www.leancrew.com/all-this/2013/10/photo-management-via-the-finder/ I've added support to detect Nikon Raw (.nef) files and to create the directories it needs i…
#!/usr/bin/python
import os, shutil
import subprocess
import os.path
from datetime import datetime
######################## Functions #########################
def photoDate(f):
"Return the date/time on which the given photo was taken."
cDate = subprocess.check_output(['sips', '-g', 'creation', f])
cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
def createFolder(f):
"Create a target folder if it does not already exist."
if not os.path.isdir(f):
os.makedirs(f)
return
###################### Main program ########################
# Where the photos are and where they're going.
sourceDir = os.environ['HOME'] + '/Desktop/Import'
destDir = os.environ['HOME'] + '/Desktop/Processed'
# The format for the new file names.
fmt = "%Y-%m-%d %H.%M.%S"
# The problem files.
problems = []
# Get all the JPEGs in the source folder.
photos = os.listdir(sourceDir)
photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' or x[-4:] == '.nef' or x[-4:] == '.NEF' ]
print "Found " + str(len(photos)) + " images to process..."
# Copy photos into year and month subfolders. Name the copies according to
# their timestamps. If more than one photo has the same timestamp, add
# suffixes 'a', 'b', etc. to the names.
for photo in photos:
original = sourceDir + '/' + photo
suffix = 'a'
ext = photo[-4:]
try:
pDate = photoDate(original)
yr = pDate.year
mo = pDate.month
createFolder(destDir + '/%04d/%02d' % (yr, mo))
newname = pDate.strftime(fmt)
duplicate = destDir + '/%04d/%02d/%s%s' % (yr, mo, newname, ext)
while os.path.exists(duplicate):
newname = pDate.strftime(fmt) + suffix
duplicate = destDir + '/%04d/%02d/%s%s' % (yr, mo, newname, ext)
suffix = chr(ord(suffix) + 1)
shutil.copy2(original, duplicate)
except ValueError:
problems.append(photo)
# Report the problem files, if any.
if len(problems) > 0:
print "Problem files:"
print "\n".join(problems)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment