Skip to content

Instantly share code, notes, and snippets.

@thomastraum
Created July 1, 2024 15:46
Show Gist options
  • Save thomastraum/92814f9044b2f401d78fd60fc2f09523 to your computer and use it in GitHub Desktop.
Save thomastraum/92814f9044b2f401d78fd60fc2f09523 to your computer and use it in GitHub Desktop.
import os
import argparse
import fnmatch
import time
from datetime import timedelta
from pathlib import Path
import logging
def delete_files(root_dir: Path, extension: str, dry_run=True):
files_processed = 0
files_deleted = 0
logger.debug(f"Searching in directory: {root_dir}")
for dirpath, dirnames, filenames in os.walk(root_dir):
current_path = Path(dirpath)
logger.debug(f"Checking directory: {current_path}")
if 'render' in current_path.parts:
for filename in fnmatch.filter(filenames, f'*.{extension}'):
file_path = current_path / filename
files_processed += 1
logger.debug(f"Processing file: {file_path}")
if dry_run:
logger.info(f"Would delete: {file_path}")
else:
try:
file_path.unlink()
logger.info(f"Deleted: {file_path}")
files_deleted += 1
except Exception as e:
logger.error(f"Error deleting {file_path}: {e}")
return files_processed, files_deleted
def main():
parser = argparse.ArgumentParser(description="Delete specified files in subdirectories of 'render'")
parser.add_argument("root_directory", help="Root directory to start searching from")
parser.add_argument("--extension", default="exr", help="File extension to delete (default: exr)")
parser.add_argument("--delete", action="store_true", help="Actually delete files (default is dry run)")
args = parser.parse_args()
dry_run = not args.delete
# Set up logging
timestamp = time.strftime("%Y%m%d-%H%M%S")
log_filename = f"file_deletion_log_{timestamp}.log"
logging.basicConfig(filename=log_filename, level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)
global logger
logger = logging.getLogger(__name__)
logger.info("=" * 50)
logger.info(f"{args.extension.upper()} File Deletion Script")
logger.info("=" * 50)
if dry_run:
logger.info("Running in dry run mode. No files will be deleted.")
else:
logger.warning("WARNING: Files will be deleted!")
start_time = time.time()
try:
# Remove any trailing quotes and backslashes
root_dir = args.root_directory.strip('"\\')
# Use Path to handle the path
root_path = Path(root_dir)
logger.info(f"Root directory: {root_path}")
logger.info(f"File extension to delete: .{args.extension}")
if not root_path.exists():
raise FileNotFoundError(f"The specified directory does not exist: {root_path}")
files_processed, files_deleted = delete_files(root_path, args.extension, dry_run)
except Exception as e:
logger.error(f"An error occurred: {e}")
return
end_time = time.time()
duration = timedelta(seconds=int(end_time - start_time))
logger.info("\n" + "=" * 50)
logger.info("Script Execution Summary")
logger.info("=" * 50)
logger.info(f"Total files processed: {files_processed}")
if dry_run:
logger.info(f"Files that would be deleted: {files_deleted}")
else:
logger.info(f"Files deleted: {files_deleted}")
logger.info(f"Time taken: {duration}")
logger.info("Script execution completed.")
logger.info(f"Log file: {log_filename}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment