In this step, a dictionary named folders is created to define different file categories and their corresponding file extensions.

This month, I will show you how to make a nice and simple document sorting script in Python (and not just because my desktop is so messy that I’ve lost track of what’s even on there anymore). I’ve broken this script down into 4 steps below:

  1. Research and Import the required libraries for the task.
  2. Check every file in the directory for the extension (e.g .doc, .xml, .jpg etc).
  3. Create folders for each file types (e.g create a ‘Images’ folder for .jpg files).
  4. Move all the files types to the correct folders (e.g all .jpg files to ‘images’).
This is part 2 of 4, in case you missed a step, all other steps will be linked below.

Step 2: Defining the File Categories

Each key in the dictionary represents a category (e.g., “Excel Spreadsheets”) and its value is a list of file extensions associated with that category (e.g., [“.xls”, “.xlsx”, “.csv”]). Additional categories and their extensions can be added by following the same pattern.


#Import OS for operating system interaction.
import os
#Import Shell Utilities for high level file operations.
import shutil

def organize_files(directory):
    #Assigned folders for different file categories.
    folders = {
        "Excel Spreadsheets": [".xls", ".xlsx", ".csv"],
        "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
        "Text Files": [".txt"],
        "Word Documents": [".doc", ".docx"]
        #To add more: "Folder Name": [".extension"]. Remember to add/remove the ',' as required.
    }

With that done, lets move onto step 3.

“The code you write makes you a programmer. The code you delete makes you a good one. The code you don’t have to write makes you a great one.” – Mario Fusco.