Python for Beginners: How to Write a Simple File Organizer Code
By: Addison Chen
Tags: Programming, Coding, Python, Learning To Code, Automation

A Run-Through of the Code Structure:

import os from pathlib import Path

After some research, I knew I would need to use the os module to manipulate the file directories. I will also need the pathlib module to access the “path ()” function that will allow me to manage the paths of the directories.

listOfDirectories = { “Picture_Folder”: [“.jpeg”, “.jpg”, “.gif”, “.png”], “Video_Folder”: [“.wmv”, “.mov”, “.mp4”,“.mpg”, “.mpeg”, “.mkv”], “Zip_Folder”: [“.iso”, “.tar”, “.gz”, “.rz”, “.7z”,”.dmg”, “.rar”, “.zip”], “Music_Folder”: [“.mp3”, “.msv”,“.wav”, “.wma”], “PDF_Folder”: [“.pdf”], }

We need to create a dictionary in Python that contains the folder name and the file extensions. Think of the dictionary as a box of chocolates holding a collection of different types of chocolates, but inside the chocolates are all different flavors. We can say the chocolates are the key, and the various fillings are the values.

Photo by Jessica Johnston on Unsplash

Below is a quick workflow explaining how I am using the Python dictionary. The beauty of this function is that you can output the values when stating the key. Here you can add more keys (folder names) and values (file extensions) that you think you would need.

Python Dictionary Workflow

File_Format_Dictionary = { final_file_format: directory for directory, file_format_stored in listOfDirectories.items() for final_file_format in file_format_stored }

Here is another use case of the Python dictionary. The variable name “File_Format_Dictionary” contains one item where “final_file_format” is the key containing the value called “directory.” The for loop will map the list of file extensions with the directory. Now we have the variables containing our long list of file extensions. We will move on to creating the logic of the code.

def organizer(): for entry in os.scandir(): if entry.is_dir(): continue file_path = Path(entry) final_file_format = file_path.suffix.lower() if final_file_format in File_Format_Dictionary: directory_path = Path(File_Format_Dictionary[final_file_format]) os.makedirs(directory_path, exist_ok=True) os.rename(file_path, directory_path.joinpath(file_path))

Now we are defining a function called “organizer.” The organizer function will start organizing your files and create the directories if it does not exist in the current location. The logic of this workflow is very straightforward as long as you understand the essential directory functions such as “scandr(),” “is_dir,” “makedirs,” and “rename.” The “scandr()” function will scan the current directory, “makedirs” will create a new file directory, and “rename” will rename the file. It continues to proceed to organize the files and renaming the folders based on the directory list.

try: os.mkdir(“Other_Folder”) except ValueError: print(“Failed to create new directory”)

You may be wondering what happens to the file extension that I did not add to the first dictionary? Well, that is why we will create another directory where any of those extensions that I forgot to add will go to the backup directory that I am creating.

for dir in os.scandir(): try: if dir.is_dir(): os.rmdir(dir) else: os.rename(os.getcwd() + ‘/’ + str(Path(dir)), os.getcwd() + ‘/Other_Folder/’ + str(Path(dir))) except ValueError:

print(“Failed to create new directory called Other Folder. File directory may already exist”)

We will need to call variable name “dir” to scan the directory then the conditional statement will check to see if the directory exists or not. If there are file extension that does not match the directory list, then it will create another folder called “Other_Folder.”

if __name__ == “__main__”: organizer()

Now to make sure the script runs, you will need to call the organizer function at the end.

Final Results:

Before I ran the script

After, I ran the script.

Overall Thoughts:

In my opinion, drawing out the workflow did increase my efficiency and helped me better understand what I need to do to get from step one to step two. The challenges I had were figuring out which “OS” or “Path” functions that I need to use to get the code to do what I want. I learn that you need to spend at least a good two hours to research and look at the syntax and structure.