How to Create a File Organizer That Sorts Files Automatically in Python
A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.
Python code
38 linesimport os
import shutil
from pathlib import Path
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Video": [".mp4", ".mkv", ".avi", ".mov"],
"Archives": [".zip", ".tar", ".gz", ".rar"],
}
def organize_folder(folder_path):
folder = Path(folder_path)
if not folder.exists() or not folder.is_dir():
print(f"Error: '{folder_path}' is not a valid directory.")
return
for item in folder.iterdir():
if item.is_file():
file_ext = item.suffix.lower()
moved = False
for category, extensions in FILE_CATEGORIES.items():
if file_ext in extensions:
target_dir = folder / category
target_dir.mkdir(exist_ok=True)
shutil.move(str(item), str(target_dir / item.name))
print(f"Moved: {item.name} -> {category}/")
moved = True
break
if not moved:
misc_dir = folder / "Misc"
misc_dir.mkdir(exist_ok=True)
shutil.move(str(item), str(misc_dir / item.name))
print(f"Moved: {item.name} -> Misc/")
if __name__ == "__main__":
organize_folder("test_folder")
Output
Moved: photo.jpg -> Images/
Moved: report.pdf -> Documents/
Moved: song.mp3 -> Audio/
Moved: video.mp4 -> Video/
Moved: backup.zip -> Archives/
Moved: readme.txt -> Documents/
How it works
The script uses pathlib.Path for cross-platform path handling and iterates over all files in the specified directory. Each file's suffix is compared case-insensitively against a dictionary of extension lists. When a match is found, the corresponding category folder is created (if missing) and the file is moved via shutil.move. Unrecognized extensions fall into a 'Misc' folder. This approach is simple, readable, and avoids external dependencies.
Common mistakes
- Forgetting to handle hidden files or system files (e.g., .DS_Store) that may also get moved.
- Using `os.rename` instead of `shutil.move` which can fail across different filesystems or drives.
- Not converting the file extension to lowercase, leading to missed matches like .JPG vs .jpg.
Variations
- Use `pathlib.Path.rglob('*.*')` to include files in nested subdirectories.
- Add a dry-run mode that only prints moves without actually moving files.
Real-world use cases
- Cleaning up a cluttered Downloads folder by automatically sorting newly downloaded files.
- Organizing photo archives from a camera SD card into date-based or type-based subfolders.
- Processing incoming files in a shared network drive where employees upload mixed-format documents.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.