Smart Directory Organizer
This Python script acts as your personal digital housekeeper. You point it at a messy folder, and it automatically scans every file, identifies its type (image, document, video, etc.), creates beautifully organized subfolders, and moves the files into their correct homes in seconds.
Features
- Automatic File Sorting: The script categorizes files based on their extensions and organizes them into subfolders like “Images,” “Documents,” “Videos,” etc.
- Customizable Organization: You can easily modify the script to include additional file types or change the folder structure to suit your needs.
- Safe File Handling: The script checks for existing files in the destination folders to prevent overwriting and ensures that all files are moved safely.
- Cross-Platform Compatibility: Works seamlessly on Windows, macOS, and Linux.
Usage
- Download the script and save it to your computer.
- Run the script and provide the path to the folder you want to organize.
- Sit back and watch as your files are neatly sorted into their respective folders.
How It Works (The Logic)
Define Categories: The script uses a Python dictionary to map file extensions (like .jpg or .pdf) to specific folder names (like “Images” or “Documents”).
Scan the Folder: It uses the os library to look at every item in the target directory.
Filter and Match: It ignores existing folders and only looks at files. It extracts the extension of each file.
Create & Move: If a file is an image, it checks if an “Images” folder exists. If not, it creates one. Then, it uses the shutil library to safely move the file into that folder. Unrecognized files are moved to an “Others” folder.
Source Code
import os
import shutil
def organize_directory(path):
"""
Organizes files in the specified directory into subfolders based on file extensions.
"""
# 1. Define the categories and their associated file extensions
FILE_CATEGORIES = {
"Images": [".jpeg", ".jpg", ".png", ".gif", ".svg", ".bmp", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".pptx", ".csv"],
"Audio": [".mp3", ".wav", ".aac", ".flac"],
"Video": [".mp4", ".avi", ".mkv", ".mov"],
"Archives": [".zip", ".tar", ".gz", ".rar", ".7z"],
"Scripts": [".py", ".js", ".html", ".css", ".sh", ".json"],
"Executables": [".exe", ".msi", ".dmg", ".apk"]
}
# 2. Verify if the provided path actually exists
if not os.path.exists(path):
print(f"❌ Error: The path '{path}' does not exist. Please check and try again.")
return
print(f"📂 Scanning and organizing files in: {path}
")
files_moved = 0
# 3. Iterate through all items in the given directory
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
# Skip directories, we only want to organize loose files
if os.path.isdir(file_path):
continue
# 4. Extract the file extension
# splitext splits "photo.jpg" into ("photo", ".jpg")
_, file_extension = os.path.splitext(filename)
file_extension = file_extension.lower() # Convert to lowercase to handle ".JPG" vs ".jpg"
# 5. Find the correct target folder for this extension
moved = False
for folder_name, extensions in FILE_CATEGORIES.items():
if file_extension in extensions:
target_folder = os.path.join(path, folder_name)
# Create the category folder if it doesn't exist yet
if not os.path.exists(target_folder):
os.makedirs(target_folder)
print(f"📁 Created new folder: {folder_name}")
# Move the file
shutil.move(file_path, os.path.join(target_folder, filename))
print(f" └── Moved: {filename} -> {folder_name}/")
moved = True
files_moved += 1
break
# 6. Handle unknown file types
if not moved:
target_folder = os.path.join(path, "Others")
if not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(file_path, os.path.join(target_folder, filename))
print(f" └── Moved: {filename} -> Others/")
files_moved += 1
# 7. Final Summary
if files_moved == 0:
print("
✨ The directory is already organized or empty!")
else:
print(f"
✅ Success! Organized {files_moved} files.")
if __name__ == "__main__":
# Prompt the user for the directory they want to clean up
print("=== Smart Directory Organizer ===")
target_path = input("Enter the absolute path of the folder to organize: ")
# Strip quotes in case the user drag-and-dropped the folder into the terminal
target_path = target_path.strip('"').strip(''')
organize_directory(target_path)
Detailed Explanation of Concepts Used
import os: This is a built-in module that lets Python interact with your Operating System. We use it to check if paths exist (os.path.exists), create folders (os.makedirs), and list what is inside a folder (os.listdir).
import shutil: The “shell utilities” module. While os is great for reading paths, shutil handles the heavy lifting of copying, moving, or deleting actual files. We use shutil.move() to relocate the files.
Dictionaries (): The FILE_CATEGORIES variable is a dictionary. It allows us to group data as Key: Value pairs. The Key is the folder name (“Images”), and the Value is a list of extensions [“.jpg”, “.png”]. This makes the code highly scalable—if you want to add a new file type, you just type it into the list rather than writing new code.
os.path.join(): Notice how we don’t use forward slashes / or backward slashes \ to create file paths? Mac/Linux use / and Windows uses . By using os.path.join(path, filename), Python automatically uses the correct slash for whatever operating system the script is currently running on.
main block: The if name == “main”: line ensures that the prompt asking the user for a path only runs if this specific script is executed directly.
How to Run It
- Open your computer’s terminal or command prompt.
- Navigate to where you saved the file.
- Run the script by typing: python file_organizer.py
- The terminal will ask you for a path.
- On Windows, it will look like: C:\Users\YourName\Downloads
- On Mac/Linux, it will look like: /Users/YourName/Downloads
- Press Enter and watch your messy folder become perfectly organized in a fraction of a second!