I once deleted a directory that I did not want to delete. I know backup, backup, backup.When I restored all the deleted files on that partition I had a mess of files multiple directories. Since the pictures of my wedding and honeymoon where in that mess, I wanted a way to sort files (or get a divorce, lol). The script below does just that. Download the source here.

# Import some modules
import os
import shutil
 
# Set some variables
path = "." # This is where the files you are that you want to sort
 
# Create a list of the directories in the path 
dirList = os.listdir(path)
 
for fname in dirList:
    # Loop through each dirList directory 
    try:
        # List all files in the directory
        listFiles = os.listdir(fname)
 
        for f in listFiles:
            # Loop through the files and split the name and extention
            ftype = f.split('.')[1]
 
            # Check the parent directory and see is the extention exsists
            # if not create a directory
            dirCheck = os.listdir('.')
 
            try:
                os.mkdir(ftype)
            except:
                pass
 
            # Create the file and directory names and move copy the file to
            # the directory named after it's extention
            source = fname + '/' + f
            dest = ftype + '/' + f
            shutil.copy(source, dest)           
    except:
        pass