Skip to content

Instantly share code, notes, and snippets.

@Tojaj
Created February 22, 2020 18:17
Show Gist options
  • Save Tojaj/a7deba7ece7ad24ebb616b9f7dcf8980 to your computer and use it in GitHub Desktop.
Save Tojaj/a7deba7ece7ad24ebb616b9f7dcf8980 to your computer and use it in GitHub Desktop.
Remove NEF files if a corresponding JPG file doesn't exist in the same directory
#!/usr/bin/env python3
import os
import glob
import string
import os.path
import argparse
def cleanup(directory, interactive=True):
# Get filenames of jpegs and nefs in the directory
jpgs = glob.glob(os.path.join(directory, "*.JPG"))
jpgs += glob.glob(os.path.join(directory, "*.jpg"))
nefs = glob.glob(os.path.join(directory, "*.NEF"))
nefs += glob.glob(os.path.join(directory, "*.nef"))
def remove_suffix(files):
"""Return a dict where key is a filename without suffix
and value is a real path"""
mapping = {}
for fn in files:
without_suffix = fn.rsplit(".", maxsplit=1)[0]
mapping[without_suffix] = fn
return mapping
# Get dicts that maps their names without suffix to full filenames
nefs_without_suffix = remove_suffix(nefs)
jpgs_without_suffix = remove_suffix(jpgs)
# Compare the sets of filenames without suffix and get extra NEFs
extra_nefs = set(nefs_without_suffix) - set(jpgs_without_suffix)
# Get a list of real paths for the extra NEFs
extra_nefs = sorted([nefs_without_suffix[x] for x in extra_nefs])
if not extra_nefs:
print("No extra NEF files")
return
print("Extra NEFs:")
print("\n".join(extra_nefs))
# Ask user if to remove them
answer = input("Do you want to remove these? [y/N]: ")
if answer.lower().strip() not in ("y", "yes", "yeah"):
print("Not removing them, exiting..")
return
# Remove them
print("Removing them..")
for fn in extra_nefs:
print (f"Removing {fn}")
os.remove(fn)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Remove *.NEF if there is no appropriate *.JPG"
)
parser.add_argument(
"directory",
metavar="DIRECTORY",
help="Directory where to do the cleanup."
)
args = parser.parse_args()
# Check args
if not os.path.isdir(args.directory):
parser.error(f"{args.directory} is not a directory!")
cleanup(args.directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment