The Palos Publishing Company

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

Build a script to clean and categorize downloads

Here’s a Python script that will clean and categorize files in your Downloads folder based on their file types. It moves files into categorized subfolders like Images, Documents, Videos, Music, Archives, Executables, and Others.

You can run this script on Windows, macOS, or Linux with Python installed.


python
import os import shutil from pathlib import Path # Define file categories FILE_CATEGORIES = { "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"], "Documents": [".pdf", ".doc", ".docx", ".txt", ".ppt", ".pptx", ".xls", ".xlsx", ".csv", ".odt"], "Videos": [".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".webm"], "Music": [".mp3", ".wav", ".aac", ".ogg", ".flac", ".m4a"], "Archives": [".zip", ".rar", ".tar", ".gz", ".7z", ".bz2"], "Executables": [".exe", ".msi", ".sh", ".bat", ".apk", ".dmg"], } # Fallback folder for uncategorized files DEFAULT_CATEGORY = "Others" def get_category(file_extension): for category, extensions in FILE_CATEGORIES.items(): if file_extension.lower() in extensions: return category return DEFAULT_CATEGORY def clean_downloads(download_path=None): # Use default Downloads path if not specified if not download_path: download_path = str(Path.home() / "Downloads") if not os.path.exists(download_path): print(f"Path does not exist: {download_path}") return for file_name in os.listdir(download_path): file_path = os.path.join(download_path, file_name) if os.path.isfile(file_path): file_extension = Path(file_path).suffix category = get_category(file_extension) target_dir = os.path.join(download_path, category) os.makedirs(target_dir, exist_ok=True) target_path = os.path.join(target_dir, file_name) # Avoid overwriting by renaming duplicates base_name, ext = os.path.splitext(file_name) counter = 1 while os.path.exists(target_path): new_name = f"{base_name}_{counter}{ext}" target_path = os.path.join(target_dir, new_name) counter += 1 shutil.move(file_path, target_path) print(f"Moved: {file_name}{category}/") print("Download folder cleanup and categorization completed.") if __name__ == "__main__": clean_downloads()

How to Use:

  1. Save the code to a .py file (e.g., clean_downloads.py).

  2. Run it with Python: python clean_downloads.py.

  3. It will automatically clean and organize your Downloads folder.

Optional Customization:

  • You can pass a custom path to clean_downloads("/path/to/your/folder").

  • Add or edit file types in FILE_CATEGORIES as needed.

Let me know if you want a scheduled task, GUI version, or logging added.

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