This content originally appeared on Level Up Coding - Medium and was authored by Dr. Ameer Hamza Mahmood
You know that feeling when your computer desktop looks less like a workspace and more like a digital junkyard?
Mine was a disaster — screenshots, random PDFs, half-finished scripts, and 27 versions of final_project_v2_REAL_final.py.
So, instead of cleaning it manually every weekend, I wrote a Python script that organizes my desktop every night automatically.
It sorts files by type, archives old ones, deletes duplicates, and even gives me a clean summary every morning.
Let’s build it step-by-step.
🧩 Step 1: The Problem
I realized that:
- 90% of my desktop clutter was temporary.
- I wasted about 10–15 minutes daily finding files.
- My downloads and desktop folders were basically black holes.
So I decided to let Python handle it:
- Detect file types.
- Move them into categorized folders.
- Delete or archive after X days.
- Schedule the whole thing to run every night.
⚙️ Step 2: Core Libraries and Setup
Here’s our toolbox:
PurposeLibraryFile operationsos, shutil, glob, pathlibSchedulingschedule, timeNotificationsplyerLoggingloggingWatching for changes (optional)watchdog
Install dependencies:
pip install schedule plyer watchdog
We’ll also use Python’s built-in libraries for most operations.
📁 Step 3: Define File Categories
Let’s define where different file types should go.
from pathlib import Path
import os, shutil
# Define your desktop path
DESKTOP_PATH = Path.home() / "Desktop"
# Define file categories
FILE_TYPES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".pptx", ".xls", ".xlsx"],
"Code": [".py", ".js", ".html", ".css", ".ipynb"],
"Archives": [".zip", ".rar", ".tar", ".gz"],
"Videos": [".mp4", ".mov", ".avi", ".mkv"],
"Music": [".mp3", ".wav", ".flac"],
"Others": []
}
This mapping will help the script decide where to place each file.
🧠 Step 4: Sorting Logic
Now, let’s scan your desktop and move files into their respective folders.
def organize_desktop():
for item in DESKTOP_PATH.iterdir():
if item.is_file():
moved = False
for folder, extensions in FILE_TYPES.items():
if item.suffix.lower() in extensions:
target_folder = DESKTOP_PATH / folder
target_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(target_folder / item.name))
moved = True
break
if not moved:
other_folder = DESKTOP_PATH / "Others"
other_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(other_folder / item.name))
This function:
- Creates folders automatically.
- Moves files to their correct location.
- Keeps your desktop clean and categorized.
⏰ Step 5: Automating Nightly Cleanup
We’ll use schedule to run the cleaning job every night at 11:59 PM.
import schedule, time
from plyer import notification
def job():
organize_desktop()
notification.notify(
title="Desktop Cleanup Complete 🧹",
message="Your desktop has been cleaned and organized.",
timeout=5
)
schedule.every().day.at("23:59").do(job)
while True:
schedule.run_pending()
time.sleep(60)
Now your desktop auto-cleans while you sleep. ✨
🔄 Step 6: Auto-Delete Old Files (Optional but Powerful)
To keep long-term cleanliness, we can automatically move old files (say, older than 30 days) into an archive or delete them.
import time
ARCHIVE_PATH = DESKTOP_PATH / "Old Files"
ARCHIVE_PATH.mkdir(exist_ok=True)
def archive_old_files(days=30):
current_time = time.time()
for folder in DESKTOP_PATH.iterdir():
if folder.is_dir():
for file in folder.iterdir():
if file.is_file() and current_time - file.stat().st_mtime > days * 86400:
shutil.move(str(file), str(ARCHIVE_PATH / file.name))
Add this line to your main job:
def job():
organize_desktop()
archive_old_files(30)
notification.notify(
title="Desktop Cleanup Complete",
message="Files older than 30 days moved to Archive.",
timeout=5
)
🔍 Step 7: Deleting Duplicate Files (Smart Mode)
Over time, we accumulate duplicates. Let’s hash files and remove copies.
import hashlib
def file_hash(file_path):
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
buf = f.read()
hasher.update(buf)
return hasher.hexdigest()
def remove_duplicates():
hashes = {}
for folder in DESKTOP_PATH.iterdir():
if folder.is_dir():
for file in folder.iterdir():
if file.is_file():
h = file_hash(file)
if h in hashes:
os.remove(file)
else:
hashes[h] = file
Now your system only keeps unique files.
📊 Step 8: Visualizing Desktop Usage
Want to see how your clutter evolves over time?
Let’s log cleanup data and visualize it.
import csv, datetime
import matplotlib.pyplot as plt
def log_cleanup(count):
with open('cleanup_log.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([datetime.datetime.now(), count])
def visualize_cleanup():
data = []
with open('cleanup_log.csv') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
data.append((row[0], int(row[1])))
dates, counts = zip(*data)
plt.plot(dates, counts, marker='o')
plt.title("Files Cleaned Over Time")
plt.xticks(rotation=45)
plt.show()
Every night’s cleanup now leaves behind a little insight.
🧠 Step 9: Adding AI — Smart Categorization with GPT
You can even get fancy — use OpenAI’s API or transformers to predict folder categories based on file names or contents.
Example (using GPT-4-like prompt):
import openai
def smart_categorize(filename):
prompt = f"Suggest the category for a file named '{filename}' (e.g., work, personal, code, media)"
response = openai.ChatCompletion.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response['choices'][0]['message']['content']
Integrate this in your organize_desktop() function for files that don’t match known types.
🧭 Step 10: Run as Background Service
You can make this a startup script using:
- Windows Task Scheduler
- macOS launchd
- Linux cron jobs
Or use Python’s built-in background trick with subprocess + nohup to keep it running silently.
🪄 Bonus: Real-Time Cleanup With watchdog
Instead of nightly runs, you can monitor file changes in real-time.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class DesktopHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
organize_desktop()
observer = Observer()
observer.schedule(DesktopHandler(), path=str(DESKTOP_PATH), recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Now files get sorted the moment they land on your desktop.
🧩 Step 11: Putting It All Together
Your final automation pipeline:
- Watches your desktop.
- Organizes files by type.
- Deletes duplicates.
- Archives old ones.
- Notifies you when done.
- Logs stats for analytics.
That’s an entire desktop management system, powered by Python.
🧘 Step 12: What I Learned
After automating this for a few weeks:
- My desktop is always empty.
- I can find any file instantly.
- My mind feels clearer — visual clutter = cognitive clutter.
- I stopped postponing cleanup altogether.
And the funny part?
Every morning when I open my laptop, I whisper:
“Good job, Python.”
🧠 Final Thoughts
This wasn’t about cleanliness — it was about mental bandwidth.
A clutter-free desktop is like a clutter-free mind.
With less time wasted searching, renaming, or deleting files, I could actually focus on building things that matter.
And all it took was ~70 lines of Python.
This Python Tool Cleans My Desktop Every Night And It’s Smarter Than Me was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Dr. Ameer Hamza Mahmood

Dr. Ameer Hamza Mahmood | Sciencx (2025-10-06T14:29:46+00:00) This Python Tool Cleans My Desktop Every Night And It’s Smarter Than Me. Retrieved from https://www.scien.cx/2025/10/06/this-python-tool-cleans-my-desktop-every-night-and-its-smarter-than-me/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.