Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python
# coding: utf-8
"""
Tool to detect and delete orphan raw files
"""
from __future__ import unicode_literals, print_function
import argparse
import sys
import os
try:
input = raw_input
except NameError:
pass
def _log(msg):
print('remove-orphan-raws: %s' % msg, file=sys.stderr)
def remove_raw_orphans(dir, pic_exts, raw_exts, batch):
to_delete = []
pic_paths_without_ext = set()
raw_full_paths = []
for file in os.listdir(dir):
name, ext = os.path.splitext(file)
ext = ext[1:].lower()
if ext in pic_exts:
pic_paths_without_ext.add(name)
continue
if ext in raw_exts:
raw_full_paths.append(file)
continue
for raw in raw_full_paths:
name = os.path.splitext(raw)[0]
if name not in pic_paths_without_ext:
to_delete.append(raw)
if not to_delete:
_log('No orphan raws identified')
return
if batch:
delete = True
else:
prompt = 'Orphans identified:\n%s\n\nDo you want to delete them? (y/n) ' % '\n'.join(to_delete)
delete = input(prompt).lower() == 'y'
if not delete:
return
for name in to_delete:
os.unlink(os.path.join(dir, name))
_log('Done')
def _split_extensions(ext):
return [s.strip().lower() for s in ext.split(',')]
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--dir', help='Target directory to search for orphans', default='.')
parser.add_argument('-p', '--pic-ext',
help='Extensions of picture files (comma separated, case insensitive)', default='jpeg,jpg')
parser.add_argument('-r', '--raw-ext',
help='Extension of raw files to be removed (comma separated, case insenstive)',
default='nef,cn2')
parser.add_argument('-b', '--batch',
help='Run in batch. No confirmation before deleting files',
action='store_true')
args = parser.parse_args()
remove_raw_orphans(
dir=args.dir,
pic_exts=_split_extensions(args.pic_ext),
raw_exts=_split_extensions(args.raw_ext),
batch=args.batch,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.