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.
We start by importing the Python modules we will use in this project. Create a file and name it
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.
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.
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
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
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,
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
if __name__ == '__main__': organizeDir()
To test this project, create 10-20 empty files using the
touch command. Add different extensions while creating the empty files (i.e.,
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.
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
Jonathan Okah is a professional freelance Python developer whose primary goal is to solve a perceived problem with the use of technology, thus making life easy for you.
Jonathan has a flair for writing and has written several blog articles for clients. He is constantly learning to improve his skills. Currently, he is studying software engineering, hoping to become a full-stack web developer.
In his leisure time, Jonathan enjoys playing games and watching the English Premier League. You can contact him for your freelance projects at Upwork.