Created
April 5, 2015 03:34
-
-
Save mmaelzer/3b876322a5c3445f3e88 to your computer and use it in GitHub Desktop.
filesorter.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from datetime import datetime | |
import os | |
from os import path, walk | |
import shutil | |
import sys | |
import time | |
if len(sys.argv) < 3: | |
print 'Usage: filesort.py [src] [dest]' | |
sys.exit(1) | |
src = sys.argv[1] | |
dest = sys.argv[2] | |
def get_dest_dir(file): | |
mtime = path.getmtime(file) | |
dtime = datetime.fromtimestamp(mtime) | |
return path.join( | |
dest, | |
dtime.strftime('%Y'), | |
dtime.strftime('%m %B') | |
) | |
def mkdir_p(dirname): | |
if not path.isdir(dirname): | |
try: | |
os.makedirs(dirname) | |
except OSError as exc: | |
if exc.errno == errno.EEXIST and path.isdir(dirname): | |
pass | |
else: | |
raise | |
files_copied = 0 | |
for (dirpath, dirnames, filenames) in walk(src): | |
for filename in filenames: | |
src_file = path.join(dirpath, filename) | |
dest_dir = get_dest_dir(src_file) | |
mkdir_p(dest_dir) | |
dest_file = path.join(dest_dir, filename) | |
shutil.copy2(src_file, dest_file) | |
files_copied += 1 | |
print 'Copied %s file%s' % (files_copied, '' if files_copied == 1 else 's') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment