⚡ Python Power Shots – 🗃️ File Organizer
Posted on: November 17, 2025
Description:
📌 Introduction
Messy folders with screenshots, PDFs, ZIPs, and random files all mixed together?
This Python Power Shot helps you auto-organize files inside a folder — either by file extension (like png, pdf, zip) or by modified date (like 2025-11-15).
With a small script and a single run, your folder becomes clean and structured in seconds.
🔎 Explanation
- The script uses pathlib to work with files and folders in a clean, cross-platform way.
- You set a target folder and choose whether to organize by:
- "extension" → moves files into subfolders like png/, pdf/, txt/
- "date" → moves files into subfolders grouped by YYYY-MM-DD (based on last modified time).
- For each file:
- It skips directories (only processes files).
- Computes the destination folder name based on your mode.
- Creates the folder if it doesn’t exist and moves the file.
This is ideal for Downloads, Desktop, or any working folder that fills up quickly.
✅ Key Takeaways
- 🗃️ Quickly organize files by type (extension) or date.
- ⚙️ Uses only the standard library (pathlib, shutil, datetime).
- 🧹 Great for cleaning up messy folders in a single script run.
Code Snippet:
from pathlib import Path
import shutil
from datetime import datetime
# --- Configuration you can tweak ---
# Folder whose files you want to organize
TARGET_FOLDER = Path("")
# Organize mode: "extension" or "date"
ORGANIZE_BY = "extension" # or "date"
# If True, print what is happening; set False for silent mode
VERBOSE = True
def get_extension_folder(file_path: Path) -> str:
"""
Return a folder name based on file extension.
Example: 'image.png' -> 'png'
If no extension, use 'no_extension'.
"""
ext = file_path.suffix.lower().lstrip(".")
return ext if ext else "no_extension"
def get_date_folder(file_path: Path) -> str:
"""
Return a folder name based on last modified date.
Example: 2025-11-15
"""
mtime = file_path.stat().st_mtime
dt = datetime.fromtimestamp(mtime)
return dt.strftime("%Y-%m-%d")
def organize_files(folder: Path, mode: str = "extension") -> None:
"""
Organize files in 'folder' by the given mode:
- "extension": group by file extension
- "date": group by last modified date
"""
if not folder.exists() or not folder.is_dir():
raise NotADirectoryError(f"Target folder does not exist or is not a directory: {folder}")
for item in folder.iterdir():
# Skip directories (only process files)
if item.is_dir():
continue
# Choose destination folder name based on mode
if mode == "extension":
dest_folder_name = get_extension_folder(item)
elif mode == "date":
dest_folder_name = get_date_folder(item)
else:
raise ValueError("ORGANIZE_BY must be 'extension' or 'date'")
dest_folder = folder / dest_folder_name
# Create destination folder if it doesn't exist
dest_folder.mkdir(exist_ok=True)
# Build full destination path (same filename, new folder)
dest_path = dest_folder / item.name
# Move the file
shutil.move(str(item), str(dest_path))
if VERBOSE:
print(f"✅ Moved: {item.name} → {dest_folder_name}/")
def main():
print(f"📂 Organizing files in: {TARGET_FOLDER}")
print(f"📁 Mode: {ORGANIZE_BY!r}\n")
organize_files(TARGET_FOLDER, ORGANIZE_BY)
print("\n🎉 File organization complete!")
if __name__ == "__main__":
main()
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!