Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 144 lines (109 sloc) 4.994 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
#
# The MIT License
#
# Copyright (c) 2009 Matthew Maravillas
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

import sys
import os
import shutil
import fnmatch
from datetime import datetime
import exif
import optparse

def main(options, args):
    
    for directory in args:
        basedir = os.path.abspath(options.destination or os.path.split(directory)[0])
        
        if options.recurse:
            for dirpath, dirnames, filenames in os.walk(directory):
                for file in fnmatch.filter(filenames, options.pattern):
                    sort_file(basedir, dirpath, file)
            
        else:
            for file in fnmatch.filter(os.listdir(directory), options.pattern):
                sort_file(basedir, directory, file)
                

def sort_file(basedir, directory, file):
    path = os.path.abspath(os.path.join(directory, file))
    
    date = None
    
    if options.use_exif:
        date = get_exif_date(path)
        
        if not date and options.verbose:
            print "No EXIF information found: %s" % path
        
    if not date:
        date = get_modification_date(path)
    
    new_directory = os.path.join(basedir,
                                 str(date.year),
                                 "%02d" % date.month)
    
    if not options.pretend:
        if not os.access(new_directory, os.F_OK):
            os.makedirs(new_directory)
            
        shutil.move(path, os.path.join(new_directory, file))
            
    if options.verbose or options.pretend:
        print path , "->", new_directory


def get_exif_date(path):
    """Return the date and time contained in the EXIF metadata for the file at path.
Returns None if the file is not an image, or contains no EXIF metadata.
"""
    try:
        exif = read_exif(path)
    except:
        print "%s could not be read" % path
    else:
        if exif:
            return datetime.strptime(str(exif["Image DateTime"]), "%Y:%m:%d %H:%M:%S")
        
    return None

def read_exif(path):
    """Return the EXIF metadata from the file at path."""
    file = open(path, 'rb')
    
    data = exif.process_file(file)
    
    return data
    
def get_modification_date(path):
    """Return the modification date & time of the file at path."""
    return datetime.fromtimestamp(os.stat(path).st_mtime)
    
    
    
if __name__ == "__main__":
    parser = optparse.OptionParser("Usage: %prog [options] directory ...")
    
    parser.add_option("-x", "--ignore-exif", dest="use_exif",
                      action="store_false", help="ignore any EXIF dates found")
    parser.add_option("-p", "--pattern", dest="pattern",
                      help="file pattern to match")
    parser.add_option("-r", "--recurse", dest="recurse",
                      action="store_true", help="recurse into subdirectories")
    parser.add_option("-d", "--destination", dest="destination",
                      help="directory that will contain sorted files")
    parser.add_option("-v", "--verbose", dest="verbose",
                      action="store_true", help="show verbose output")
    parser.add_option("-P", "--pretend", dest="pretend",
                      action="store_true", help="don't actually move files")
    
    parser.set_defaults(use_exif=True,
                        pattern="*.*",
                        recurse=False,
                        destination=None,
                        verbose=False,
                        pretend=False)
    
    (options, args) = parser.parse_args()
    
    if len(args) < 1:
        parser.error("Missing path argument")
    
    if options.verbose:
        if options.use_exif:
            print "Using EXIF dates"
        
        print "File pattern:", options.pattern
        
        if options.recurse:
            print "Recursing into subdirectories"
        
        print "Destination directory: %s" % (options.destination or "Default")
           
    main(options, args)
Something went wrong with that request. Please try again.