Next, the organize_files function is defined to organize the files in the specified directory.
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:
Research and Import the required libraries for the task.Check every file in the directory for the extension (e.g .doc, .xml, .jpg etc).- Create folders for each file types (e.g create a ‘Images’ folder for .jpg files).
- Move all the files types to the correct folders (e.g all .jpg files to ‘images’).
Step 3: Organizing the Files
It takes the directory parameter, which represents the path to the directory where the files are located. Within the function, a loop is used to iterate through each file in the directory. The os.listdir(directory) function returns a list of all files and folders in the specified directory.
#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.
}
#Go through every file in the specifed directory.
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
#Get the file extension
extension = os.path.splitext(filename)[1]
#Check the extension against each category above and move the file.
for folder, extensions in folders.items():
if extension.lower() in extensions:
target_folder = os.path.join(directory, folder)
if not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(os.path.join(directory, filename), os.path.join(target_folder, filename))
With that done, lets put it all together and move onto the final step!
“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.