Categories We Write About

Build a Python script to mass-delete files by date

Here’s a Python script that allows you to mass-delete files based on their modification date. It recursively scans a given directory and deletes files older than a specified number of days or before a specific date.

python
import os import time from datetime import datetime, timedelta def delete_files_by_age(directory, days_old=None, before_date=None, dry_run=True): """ Deletes files older than `days_old` days or before a specific `before_date`. Args: directory (str): The root directory to search in. days_old (int, optional): Delete files older than this number of days. before_date (str, optional): Delete files modified before this date (format: 'YYYY-MM-DD'). dry_run (bool): If True, only lists files to be deleted. Set to False to actually delete. """ if not os.path.isdir(directory): print(f"Directory does not exist: {directory}") return if not days_old and not before_date: print("You must specify either 'days_old' or 'before_date'.") return if before_date: try: cutoff = datetime.strptime(before_date, "%Y-%m-%d").timestamp() except ValueError: print("Date must be in YYYY-MM-DD format.") return else: cutoff = time.time() - (days_old * 86400) deleted_files = [] for root, _, files in os.walk(directory): for file in files: filepath = os.path.join(root, file) try: mtime = os.path.getmtime(filepath) if mtime < cutoff: deleted_files.append(filepath) if not dry_run: os.remove(filepath) except Exception as e: print(f"Error handling file {filepath}: {e}") action = "Would delete" if dry_run else "Deleted" for file in deleted_files: print(f"{action}: {file}") print(f"nTotal files {'to be deleted' if dry_run else 'deleted'}: {len(deleted_files)}") # Example usage: if __name__ == "__main__": # Customize these values target_directory = "/path/to/your/folder" delete_files_by_age( directory=target_directory, days_old=30, # Files older than 30 days # before_date="2023-12-31", # Alternatively, delete before this date dry_run=True # Set to False to actually delete files )

Features:

  • days_old: Deletes files older than N days.

  • before_date: Deletes files before a specific date (overrides days_old).

  • dry_run: Preview which files would be deleted before actual deletion.

How to Run:

  1. Replace "/path/to/your/folder" with your actual directory.

  2. Set dry_run=False after testing to delete files.

Let me know if you need this adapted for file creation dates, only specific file types, or GUI-based execution.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About