Organize Files by Suffix: How I Created a Python Script to Automate a Boring Task

Does the nature of your work involve going through a folder full of dozens, hundreds, or even thousands of files? What if you were told to organize those files according to their extension in a subdirectory, imagine how boring and time-consuming such a task would be if the files contain dozens of extensions!

What if you could find a way to automate these boring tasks and have them done instantly? All these and more are possible with Python.

βš”οΈ Coding Challenge: In this tutorial, I will show you how I created a Python script to organize files according to their extensions and have them stored in a subdirectory. Note that the script will only work if the name of your files has an extension.

Getting Started

We start by importing the Python modules we will use in this project. Create a file and name it fileOrganizer.py.

import os
from pathlib import Path

These two modules are invaluable tools for file management. Another one is the shutil module but we will not use it in this project. These modules can be used to create a file manager app with Python.

The os module provides a portable way to interact with the operating system. Using the os module, you can create or delete a directory, change to a directory, and so on.

We will use the Path class from the pathlib module to get the path of a particular file for easy manipulation. The Path class also allows writing operations on different filesystem paths.

Defining the subdirectories and extensions

Next, we will create a dictionary object where the keys represent the name of a subdirectory for a particular file extension and the values are the file extension.

SUBDIR = {
    "PythonPro": [".py"],
    "CSV": ['.csv'],
    'JavaScript': ['.js']
   }

This is the only script you have to modify based on the task you are performing. We imagine we have several files with just three extensions for this project. Notice that the values are lists. Thus, if you want a subdirectory to have two or more file extensions, you simply have to include them in the list.

Creating the pickDir() function

The pickDir() function will take a string, the file extension, and returns its subdirectory.

def pickDir(value):

    for category, extension in SUBDIR.items():
        for suffix in extension:
            if suffix == value:
                return category

So, if it takes the .py extension, for example, it will return the PythonPro subdirectory.

Creating the organizeDir() function

This function is the main function that organizes the files into several subdirectories.

def organizeDir():

    for item in os.scandir():

        if item.is_dir():
            continue

        filePath = Path(item)
        fileType = filePath.suffix.lower()
        directory  = pickDir(fileType)

        
        if directory == None:
            continue
        directoryPath = Path(directory)

      
        if directoryPath.is_dir() != True:
            directoryPath.mkdir()

        filePath.rename(
        directoryPath.joinpath(filePath)

We use the scandir() method to scan all files in the current directory. The method is itself an iterator. So, we loop through all the files. If there is a folder in each iteration, it skips it. It then gets the path object of the files and saves them in the variable, filePath.

Next, we call the .suffix property to get the file extension of each file. Then, we pass the extension to the pickDir() function which returns the name of the subdirectory of the particular extension. It skips the file with no extension and gets the path of the subdirectories.

Next, it checks whether the name of the subdirectory you defined is already existing in the current directory. If not, it creates the subdirectory using the .mkdir() method. Once the subdirectory is created, it renames the files and moves them to the subdirectory.

To enable the script to run, we use the special __name__ variable.

if __name__ == '__main__':
    organizeDir()

Testing

To test this project, create 10-20 empty files using the touch command. Add different extensions while creating the empty files (i.e., touch image.png, data.csv, index.html).

Open the fileOrganizer.py and modify the SUBDIR variable as already explained. Then, run python3 fileOrganizer.py in the terminal, and see the files organized in a blink of an eye.

Conclusion

We have learned how to automate a boring task using Python. Are there other boring office tasks taking all your day? Why not automate them using Python!

There are a lot of boring tasks other than file management that you can automate with Python such as scraping a webpage, and getting the results in CSV format. Learning to automate such tasks can increase your productivity.

πŸ’‘ Recommended: Convert HTML Table to CSV in Python