Skip to content

Instantly share code, notes, and snippets.

@sosi-deadeye
Created March 5, 2020 10:51
Show Gist options
  • Save sosi-deadeye/6de143b516a6eca8f5c1f73d0557066d to your computer and use it in GitHub Desktop.
Save sosi-deadeye/6de143b516a6eca8f5c1f73d0557066d to your computer and use it in GitHub Desktop.
"""
Delete everything, pictures are excluded.
"""
from argparse import ArgumentParser
from pathlib import Path
from textwrap import dedent
LOSS_LESS_FORMATS = (
".png",
".bmp",
".gif",
".tiff",
)
LOSSY_FORMATS = (
".jpg",
".webp",
)
RAW_FORMATS = (
".raw",
".nef",
".crw",
".cr2",
".cr3",
)
IMG_EXTENSIONS = sorted(LOSS_LESS_FORMATS + LOSSY_FORMATS + RAW_FORMATS)
def traverse_files(root, exclude):
for file in Path(root).rglob("*"):
excluded = file.suffix.casefold() in exclude
yield excluded, file
def delete_files(root, exclude):
for is_excluded, file in traverse_files(root, exclude):
if not is_excluded:
print("Deleting file", file)
try:
file.unlink()
except PermissionError:
print("No permission to delete", file)
def count(root, exclude):
excluded = 0
included = 0
for is_excluded, file in traverse_files(root, exclude):
if is_excluded:
excluded += 1
else:
included += 1
print(dedent(
f"""
Files total : {excluded + included:>8d}
Files to delete: {included:>8d}
Files excluded : {excluded:>8d}
"""
))
if __name__ == "__main__":
parser = ArgumentParser(description=__doc__)
parser.add_argument("root", help="Root directory where the files should deleted")
parser.add_argument(
"--exclude", nargs="+", choices=IMG_EXTENSIONS, default=IMG_EXTENSIONS
)
parser.add_argument(
"-c", action="store_true", help="Count how many files to delete"
)
args = parser.parse_args()
if args.c:
count(args.root, args.exclude)
else:
delete_files(args.root, args.exclude)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment