photo 1555066931 4365d14bab8c
  • Education
  • Technology
  • How to Automate Boring File Tasks with Python

    If you’ve ever had to rename 100 files, move photos into different folders, or combine multiple CSV files, you know how mind-numbing it can be.The good news? You can write a 10-line Python script to do it for you in seconds. Today, we’re going to look at a simple Python script that organizes your downloads folder by putting images in one folder and documents in another.

    The Python Script

    import os
    import shutil
    
    # Set your target directory here
    target_dir = "/path/to/your/downloads/folder"
    
    # Create new folders if they don't exist
    os.makedirs(os.path.join(target_dir, "Images"), exist_ok=True)
    os.makedirs(os.path.join(target_dir, "Documents"), exist_ok=True)
    
    # Loop through files in the directory
    for filename in os.listdir(target_dir):
        file_path = os.path.join(target_dir, filename)
        
        # Skip directories
        if os.path.isfile(file_path):
            # Check file extension
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                shutil.move(file_path, os.path.join(target_dir, "Images", filename))
            elif filename.lower().endswith(('.pdf', '.docx', '.txt')):
                shutil.move(file_path, os.path.join(target_dir, "Documents", filename))
    
    print("Organization complete!")

    How it works:

    • os and shutil: These are built-in Python libraries. os lets us interact with the operating system (like reading folders), and shutil lets us move files.
    • os.makedirs: This creates our “Images” and “Documents” folders. The exist_ok=True part ensures Python doesn’t throw an error if the folder already exists.
    • The for loop: We look at every single file. If it ends with an image extension, we move it to Images. If it’s a document, we move it to Documents.
    What boring task are you going to automate first? Let me know in the comments below!
    2 mins