Script for sorting your photos

Quick one this, and apologies for not posting for ages; I’ve been busy.

I love Dropbox camera upload; I come home from a trip, all photo’d up, and my iPhone syncs to my PC automagically. With a standard DSLR or compact camera all I have to do is connect it to the PC and it starts the syncing process.

Thing is, that with the amount of photos I take this swiftly becomes unmanageable. So I knocked up a script to watch the filesystem and organise the files automagically. I’ve added this to my machine’s startup;

import os, time, signal, threading

photobucket = "C://Users/mel//Dropbox//Camera Uploads//"


class Watcher(threading.Thread):
    path_to_watch = ""
    before = None
    action = None

    def __init__(self, path):
        threading.Thread.__init__(self)
        self.path_to_watch = path
        self.before = self.files_to_timestamp(path)

    def files_to_timestamp(self, path):
        files = [os.path.join(path, f) for f in os.listdir(path)]
        return dict ([(f, os.path.getmtime(f)) for f in files])

    def run(self):
        while 1:
            time.sleep(2)
            after = self.files_to_timestamp(self.path_to_watch)

            added = [f for f in after.keys() if not f in self.before.keys()]
            removed = [f for f in self.before.keys() if not f in after.keys()]
            modified = []

            for f in self.before.keys():
                if not f in removed:
                    if os.path.getmtime(f) != self.before.get(f):
                        modified.append(f)


            if added: print "Added: ", ", ".join(added)
            if removed: print "Removed: ", ", ".join(removed)
            if modified: print "Modified ", ", ".join(modified)

            if self.action is not None:
                for newFile in added:
                    self.action(newFile)
            self.before = after

if __name__ == "__main__":
    def handleFile(filename):
        dt_mod = time.gmtime(os.path.getctime(filename))
        dir_name_to_move = str(dt_mod.tm_year) + "." + str(dt_mod.tm_mon).zfill(2)
        if not os.path.exists(dir_name_to_move):
            os.mkdir(dir_name_to_move)
        os.rename(filename, os.path.join(dir_name_to_move, filename))

    os.chdir(photobucket)
    for dirpath, dirnames, filenames in os.walk(photobucket):
        if dirpath == photobucket:
            for filename in filenames:
                handleFile(filename)

    watcher = Watcher(photobucket)
    watcher.action = lambda path : handleFile(path)
    watcher.start()


About this entry