Skip to content

Instantly share code, notes, and snippets.

@wlinds
Created September 2, 2024 21:29
Show Gist options
  • Save wlinds/93cd8d53ea30357e58731bc9bdc987aa to your computer and use it in GitHub Desktop.
Save wlinds/93cd8d53ea30357e58731bc9bdc987aa to your computer and use it in GitHub Desktop.
Python CLI tool to remove files based on file extension
import os, fnmatch, argparse
def clean_it(root_dir, file_extension):
"""
Walks through all subdirs of the given directory and deletes files with the specified extension.
Also removes any empty directories left after the file deletion.
:param root_dir: The root directory to start the search from.
:param file_extension: The file extension to look for and delete.
"""
absolute_root_dir = os.path.abspath(root_dir)
print(f"Are you sure you want to delete all '{file_extension}' files in '{absolute_root_dir}'? (yes/no)")
confirmation = input().strip().lower()
if confirmation.lower() != 'yes':
print("Operation canceled.")
return
for dirpath, dirnames, filenames in os.walk(absolute_root_dir, topdown=False):
for filename in filenames:
if fnmatch.fnmatch(filename, f"*{file_extension}"):
file_path = os.path.join(dirpath, filename)
try:
os.remove(file_path)
print(f"Deleted: {file_path}")
except Exception as e:
print(f"Failed to delete {file_path}: {e}")
# Avoid removing the root directory itself
if dirpath != absolute_root_dir:
if not os.listdir(dirpath):
try:
os.rmdir(dirpath)
print(f"Deleted: {dirpath}")
except Exception as e:
print(f"Failed to remove directory {dirpath}: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Deletes files with a specific extension in a dir and its subdirectories. Removes any empty directories left behind.")
parser.add_argument("root_dir", nargs="?", default=".", help="The root dir to start the search from. Defaults to the current dir.")
parser.add_argument("extension", type=str, help="The file extension to delete (e.g., .txt).")
args = parser.parse_args()
clean_it(args.root_dir, args.extension)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment