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 1: Import the Required Libraries
The first step in the code is to import the necessary libraries. The ‘os’ library is imported to interact with the operating system, allowing the script to perform file-related operations. The ‘shutil’ library is imported to access high-level file operations, such as moving files.
#Import OS for operating system interaction.
import os
#Import Shell Utilities for high level file operations.
import shutil
def organize_files(directory):
With that done, lets move onto step 2 and create our first variable ‘organise_files’.
“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.