Skip to content

Instantly share code, notes, and snippets.

@terrettaz
Last active March 18, 2018 16:07
Show Gist options
  • Save terrettaz/87f067402136dd9f05e46cea388709de to your computer and use it in GitHub Desktop.
Save terrettaz/87f067402136dd9f05e46cea388709de to your computer and use it in GitHub Desktop.
Find orphan files based on the extension and move them into directory, typically used for removing raw picture where jpeg have been removed
#!/usr/bin/env python
import os, os.path
import argparse
parser = argparse.ArgumentParser(description='Find orphan files based on the extension and move them into directory')
parser.add_argument('--dir', nargs='?', default=os.getcwd(), help='Directory to process (default CWD)')
parser.add_argument('--dest', nargs='?', default='orphans', help='Destination directory (default orphans)')
parser.add_argument('--delete', action='store_true', default=False, help='Delete files instead of backing them up')
parser.add_argument('--sensitive', action='store_true', default=False, help='Case sensitive for extensions')
parser.add_argument('--dry-run', action='store_true', default=False, help='Make a simulation (do not effectivily move files)')
parser.add_argument('--no-checks', action='store_true', default=False, help='Disable validation if the there is too many orphans')
parser.add_argument('base_extension', help='Base extension')
def find_extension(f):
base, extension = os.path.splitext(f)
if extension and len(extension) > 1:
return extension[1:]
return ''
def accept_base(args):
if not args.sensitive:
return lambda f: find_extension(f).upper() == args.base_extension.upper()
return lambda f: find_extension(f) == args.base_extension
def is_file_with_ext(f):
base, extension = os.path.splitext(f)
return base != '' and extension != ''
def orphans(bases):
base_names = map(lambda f: os.path.splitext(f)[0], bases)
return lambda f: os.path.splitext(f)[0] not in base_names
def process_orphan(f, args):
path = os.path.join(args.dir, f)
if args.delete:
print 'Deleting ' + f + ' ...'
#if not args.dry_run:
# os.remove(path)
else:
dest = os.path.join(args.dir, args.dest)
if not os.path.exists(dest): os.makedirs(dest)
print 'Moving ' + f + ' to ' + dest + ' ...'
if not args.dry_run:
os.rename(os.path.join(args.dir, f), os.path.join(dest, f))
def ratio(files, bases):
f = float(len(files))
b = float(len(bases))
return (f - b) / f
if __name__ == '__main__':
args = parser.parse_args()
files = [f for f in os.listdir(args.dir)
if os.path.isfile(os.path.join(args.dir, f)) and is_file_with_ext(f)]
bases = filter(accept_base(args), files)
ratio = ratio(files, bases)
if not args.no_checks and ratio > 0.7:
if raw_input('> There are many orphans, do you want to continue ? [y/n]: ') != 'y':
import sys
sys.exit(1)
others = filter(orphans(bases), files)
for f in others: process_orphan(f, args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment