Project: a script that tidies your files

A Python script that walks a folder and moves each file into a subfolder by its type. With pathlib, shutil and a test mode.

The Downloads folder is chaos. This project is a script that tidies it by itself: photos to Images, PDFs to Documents, etc. You practise walking folders, working with paths and moving files safely.

Simulator

Aquí tienes una lista de archivos de mentira (edítala si quieres). Simular muestra el plan sin tocar nada; Organizar lo aplica:

Step 1: decide the folder for each type

CARPETAS = {
    ".jpg": "Imagenes", ".jpeg": "Imagenes", ".png": "Imagenes", ".gif": "Imagenes",
    ".pdf": "Documentos", ".txt": "Documentos", ".docx": "Documentos", ".xlsx": "Documentos",
    ".mp3": "Audio", ".wav": "Audio",
    ".mp4": "Video", ".mov": "Video",
}

Step 2: walk the folder with pathlib

from pathlib import Path

CARPETA = Path.home() / "Downloads"

for archivo in CARPETA.iterdir():
    if archivo.is_dir():
        continue                       # saltar subcarpetas
    destino_nombre = CARPETAS.get(archivo.suffix.lower())
    if destino_nombre is None:
        print(f"?  {archivo.name} (extensión desconocida)")
        continue
    print(f"{destino_nombre}/  <-  {archivo.name}")

Step 3: move with shutil (and create the folder)

import shutil

def mover(archivo: Path, carpeta: str, dry_run: bool):
    destino = archivo.parent / carpeta
    destino.mkdir(exist_ok=True)        # no falla si ya existe
    if dry_run:
        print(f"[simulado] {archivo.name} -> {carpeta}/")
    else:
        shutil.move(str(archivo), str(destino / archivo.name))
        print(f"movido {archivo.name} -> {carpeta}/")

Step 4: the test mode and the arguments

import sys

def main():
    dry_run = "--dry-run" in sys.argv
    for archivo in CARPETA.iterdir():
        if archivo.is_file():
            carpeta = CARPETAS.get(archivo.suffix.lower())
            if carpeta:
                mover(archivo, carpeta, dry_run)

if __name__ == "__main__":
    main()

# uso:
#   python organizar.py --dry-run    (solo enseña qué haría)
#   python organizar.py              (lo hace de verdad)

Where to go next

  • If a file with that name already exists in the target, add a number: foto (2).jpg.
  • Organise by date as well as by type (2024-05/ folders).
  • Schedule it to run by itself every day (cron on Linux, Task Scheduler on Windows).
  • Log what it does to an organizar.log file.