SoFunction
Updated on 2025-05-22

Use python to write automatic sorting and download directory tools

Start with the simplest category

My goal is also very simple: according to the file type, move the file to the corresponding subfolder, such as PDF to put documents, images to images, and install packages to put installers.

Use firstosandshutilI wrote the most basic version, probably like this:

import os
import shutil

DOWNLOAD_DIR = ("~/Downloads")

# Custom classification rulesFILE_CATEGORIES = {
    "documents": [".pdf", ".docx", ".xlsx"],
    "images": [".jpg", ".png", ".gif"],
    "installers": [".exe", ".msi", ".dmg"],
    "compressed": [".zip", ".rar", ".7z"]
}

for filename in (DOWNLOAD_DIR):
    filepath = (DOWNLOAD_DIR, filename)
    
    if (filepath):
        continue  # Skip folder
    ext = (filename)[1].lower()

    for category, extensions in FILE_CATEGORIES.items():
        if ext in extensions:
            target_dir = (DOWNLOAD_DIR, category)
            (target_dir, exist_ok=True)
            (filepath, (target_dir, filename))
            break

This script only uses twenty or thirty lines of code. After executing, the entire download directory is not so messy and looks much more refreshing.

Later, some small functions were added

After sorting out the types, I added two simple functions:

1. Archive by time

For example, I downloaded some old files, and maybe I can't use them for a long time. I want to classify them by month to facilitate cleaning in the future. Add onegetmtimeJust do it:

from datetime import datetime

mtime = (filepath)
folder_name = (mtime).strftime("%Y-%m")
target_dir = (DOWNLOAD_DIR, folder_name)

2. Clean up temporary files N days ago

picture.log.tmpI hope to automatically delete this temporary file from 30 days ago. Just judge the modification time:

import time

now = ()
if ext in [".log", ".tmp"]:
    if now - (filepath) > 30 * 86400:
        (filepath)

This function is simple, but it is easy to use. Especially when I often take screenshots, the system will automatically save them to the download directory. These pictures will be meaningless after being kept for a long time, and it is best to be automatically cleared.

Some attempts afterwards

Later I tried adding a little extension:

  • useargparseSupports input directory paths and retention days from the command line
  • For file change monitoringwatchdog, can organize newly downloaded files in real time

Someone also asked me if this script has to be run manually every time?

Actually, no,Can be executed regularly, The method is very simple, two ideas:

Method 1: Use schedule + infinite loop (suitable for machines that have been hanging all the time)

import schedule
import time
import your_cleanup_script  # Encapsulate your sorting function here
def job():
    print("Start organize the download folder...")
    your_cleanup_script.run()

# Perform once every morning at 8:00().("08:00").do(job)

while True:
    schedule.run_pending()
    (60)

This is suitable for you to keep your computer on, such as a company PC, or you plan to put it on the server to run.

Method 2: Use the system-owned timing tasks

This is more practical:

macOS / Linux: Use crontab

  • Open the terminal and entercrontab -e
  • Add a line of configuration, such as executing scripts at 8 o'clock every day:
0 8 * * * /usr/bin/python3 /Users/yourname/scripts/clean_downloads.py

Windows: Use Task Scheduler

  • Open Task Scheduler
  • Create basic tasks
  • Set the trigger time
  • Select "Start Program" to perform the operation, fill in the path of your Python interpreter, and fill in the path of your script with the parameters.

I personally useTask Scheduler, clean it once every morning, and ignore it after setting it up, so worry-free.

at last

I still use this little script every day. Writing it is not a "big project", it just wants to solve a small daily problem. It's not that cool to use, but it's really worry-free.

Since using it, my download folder has finally become quiet. I have never been hit by invoices 2 years ago, screenshots 3 weeks ago, and compressed double-teams that I just came down.

If you have similar problems, you can try writing one by yourself. No need to be complicated, just run. Writing some scripts is really one of the cheapest cures.

The above is the detailed content of using python to write the automatic sorting and download directory tool. For more information about python's automatic sorting and download directory, please pay attention to my other related articles!