The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create an automatic folder cleaner

Creating an automatic folder cleaner can be very useful for managing disk space and keeping your files organized. Below is a Python script that automatically cleans a specified folder by deleting files older than a certain number of days. This script can be run periodically (e.g., via a scheduled task or cron job).


Automatic Folder Cleaner in Python

python
import os import time from datetime import datetime, timedelta def clean_folder(folder_path, days_old): """ Delete files older than `days_old` days in the specified folder. :param folder_path: Path to the folder to clean. :param days_old: Files older than this many days will be deleted. """ now = time.time() cutoff = now - (days_old * 86400) # Convert days to seconds if not os.path.exists(folder_path): print(f"Folder does not exist: {folder_path}") return deleted_files = 0 for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) # Only process files (not directories) if os.path.isfile(file_path): file_modified = os.path.getmtime(file_path) # Check if file is older than cutoff time if file_modified < cutoff: try: os.remove(file_path) deleted_files += 1 print(f"Deleted: {file_path}") except Exception as e: print(f"Error deleting {file_path}: {e}") print(f"Total files deleted: {deleted_files}") if __name__ == "__main__": # Customize these variables folder_to_clean = "/path/to/your/folder" days_threshold = 30 # Files older than 30 days will be deleted clean_folder(folder_to_clean, days_threshold)

How It Works:

  • The script checks all files in the given folder.

  • It deletes files last modified more than days_old days ago.

  • It skips folders and only deletes files.

  • Prints progress and summary.

How to Use:

  1. Change the value of folder_to_clean to the folder you want cleaned.

  2. Set days_threshold to the age in days after which files will be deleted.

  3. Run the script manually or set it up as a scheduled task (Windows Task Scheduler or Linux cron job).


If you want, I can help you create a version that moves files to the recycle bin instead of permanent deletion, or one that archives old files rather than deleting them. Just let me know!

Share this Page your favorite way: Click any app below to share.

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

We respect your email privacy

Categories We Write About