[Python] How can I organize files by type and date using Python without errors? [closed]

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a Python script to organize files from one folder into another. The plan is to create folders based on file types (like PDF, JPEG) and then subfolders for year and month of last modification.

    Here is my code:

    import os
    import shutil
    from datetime import datetime

    source_dir = 'C:/Users/ajay/Documents/messy_files'
    dest_dir = 'C:/Users/ajay/Documents/sorted_files'

    for file in os.listdir(source_dir):
    if os.path.isfile(os.path.join(source_dir, file)):
    ext = os.path.splitext(file)[1].lower().replace('.', '')
    mod_time = os.path.getmtime(os.path.join(source_dir, file))
    mod_date = datetime.fromtimestamp(mod_time)
    year = mod_date.strftime('%Y')
    month = mod_date.strftime('%m')

    new_path = os.path.join(dest_dir, ext, year, month)
    os.makedirs(new_path, exist_ok=True)

    shutil.move(os.path.join(source_dir, file), os.path.join(new_path, file))


    How can I improve this script so it doesn’t throw errors like FileNotFoundError or overwrite files that already exist? Also, is there a better or faster way to organize thousands of files?

    Continue reading...

Compartilhe esta Página