Skip to content

Instantly share code, notes, and snippets.

@en0
Created January 13, 2014 04:22
Show Gist options
  • Save en0/8394676 to your computer and use it in GitHub Desktop.
Save en0/8394676 to your computer and use it in GitHub Desktop.
Organize files into a directory tree using time stamps encoded in the file name.
#!/bin/env python3
import argparse
import sys
import os
import shutil
from datetime import datetime
def migrate(**kwargs):
"""Organize files in a given source to a directory structure
Keyword Arguments:
source - The source directory to read items from
dest - The prefix of the target directory
srcfmt - The format used to parse the source items
dstfmt - The format used to create the target structure
pretend - If set, no files will be moved
"""
kwargs.setdefault('srcfmt', '%Y%m%d_%H%M%S.jpg')
kwargs.setdefault('dstfmt', '%Y-%b')
kwargs.setdefault('pretend', False)
if 'source' not in kwargs.keys():
raise KeyError('Key Word \'source\' is required')
if 'dest' not in kwargs.keys():
raise KeyError('Key Word \'dest\' is required')
src = kwargs['source']
dst = kwargs['dest']
srcfmt = kwargs['srcfmt']
dstfmt = kwargs['dstfmt']
pretend = kwargs['pretend']
print("-----------------------------")
print("Just Pretending" if pretend else "Migrating Files")
print("-----------------------------")
for dstdir,srcpath in getMigrationMap(src,dst,srcfmt,dstfmt):
if not pretend:
migrateFile(dstdir, srcpath)
else:
print("Would Move '{}' to '{}'".format(srcpath,dstdir))
def migrateFile(dstdir, srcpath):
"""Move a file from the source directory to the destination directory
On move, if the target directory does not exist, it will be created
Arguments:
dstdir - The target directory to move the file to
srcpath - The path of the file to be moved
"""
if not os.path.exists(dstdir):
os.makedirs(dstdir)
shutil.move(srcpath,dstdir)
def getMigrationMap(src,dst,srcfmt,dstfmt):
"""Determin the source and targets of files to migrate
For each file in the source directory, parse the file name and create the output
details bassed on the input file name.
Arguments:
src - the source path to read items from
dst - the prefix of the target path
srcfmt - the format to parse the filenames
dstfmt - the format to create the target directory
Returns:
A tuple (target path, source file)
"""
for dirpath,_,filenames,_ in os.fwalk(src):
for filename in filenames:
try:
dstpath = datetime.strptime(filename,srcfmt).strftime(dstfmt)
except ValueError:
print("Warning: '{}' didnt match source format".format(filename))
continue
yield (
"{}/{}".format(dst.strip('/'),dstpath),
"{}/{}".format(dirpath.strip('/'),filename)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Organize images into a folder structure based on its name.")
parser.add_argument('source', help="The source directory")
parser.add_argument('dest', help="The destination directory")
parser.add_argument('--srcfmt', default='%Y%m%d_%H%M%S.jpg',
help='specify the format of the input file\'s name.')
parser.add_argument('--dstfmt', default='%Y-%b',
help='specify the sub directory folder name formats.')
parser.add_argument('--pretend', action='store_true')
args = parser.parse_args(sys.argv[1:])
migrate(
source = args.source,
dest = args.dest,
srcfmt = args.srcfmt,
dstfmt = args.dstfmt,
pretend = args.pretend
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment