Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Junk File Organizer in Python?
Organizing files by type can save time when dealing with cluttered directories. This Python script automatically sorts files into appropriate folders based on their extensions and removes empty directories.
File Type Configuration
First, we define which file extensions belong to each category ?
import os
from pathlib import Path
DIRECTORIES = {
"HTML": [".html5", ".html", ".htm", ".xhtml"],
"IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", ".svg",
".heif", ".psd"],
"VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng",
".qt", ".mpg", ".mpeg", ".3gp"],
"DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods",
".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox",
".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt",
".pptx"],
"ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z",
".dmg", ".rar", ".xar", ".zip"],
"AUDIO": [".aac", ".aa", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3",
".msv", ".ogg", ".oga", ".raw", ".vox", ".wav", ".wma"],
"PLAINTEXT": [".txt", ".in", ".out"],
"PDF": [".pdf"],
"PYTHON": [".py"],
"XML": [".xml"],
"EXE": [".exe"],
"SHELL": [".sh"]
}
# Create a mapping from file extension to folder name
FILE_FORMATS = {file_format: directory
for directory, file_formats in DIRECTORIES.items()
for file_format in file_formats}
print("Sample mappings:")
for ext in [".py", ".jpg", ".pdf"]:
print(f"{ext} ? {FILE_FORMATS.get(ext, 'OTHER-FILES')}")
Sample mappings: .py ? PYTHON .jpg ? IMAGES .pdf ? PDF
File Organization Function
The main function scans the current directory and moves files to appropriate folders ?
def organize_files():
"""Organize files in current directory by type"""
# First pass: organize known file types
for entry in os.scandir():
if entry.is_dir():
continue
file_path = Path(entry)
file_format = file_path.suffix.lower()
if file_format in FILE_FORMATS:
# Create target directory if it doesn't exist
directory_path = Path(FILE_FORMATS[file_format])
directory_path.mkdir(exist_ok=True)
# Move file to appropriate folder
file_path.rename(directory_path.joinpath(file_path.name))
print(f"Moved {file_path.name} to {directory_path}")
# Create OTHER-FILES folder for remaining files
other_files_path = Path("OTHER-FILES")
other_files_path.mkdir(exist_ok=True)
# Second pass: move remaining files to OTHER-FILES
for entry in os.scandir():
if not entry.is_dir():
file_path = Path(entry)
target_path = other_files_path / file_path.name
file_path.rename(target_path)
print(f"Moved {file_path.name} to OTHER-FILES")
# Remove empty directories (optional)
for entry in os.scandir():
if entry.is_dir():
try:
os.rmdir(entry.path)
print(f"Removed empty directory: {entry.name}")
except OSError:
# Directory not empty, skip
pass
Complete Script
Here's the full file organizer script ?
import os
from pathlib import Path
DIRECTORIES = {
"HTML": [".html5", ".html", ".htm", ".xhtml"],
"IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", ".svg",
".heif", ".psd"],
"VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng",
".qt", ".mpg", ".mpeg", ".3gp"],
"DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods",
".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox",
".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt",
".pptx"],
"ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z",
".dmg", ".rar", ".xar", ".zip"],
"AUDIO": [".aac", ".aa", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3",
".msv", ".ogg", ".oga", ".raw", ".vox", ".wav", ".wma"],
"PLAINTEXT": [".txt", ".in", ".out"],
"PDF": [".pdf"],
"PYTHON": [".py"],
"XML": [".xml"],
"EXE": [".exe"],
"SHELL": [".sh"]
}
FILE_FORMATS = {file_format: directory
for directory, file_formats in DIRECTORIES.items()
for file_format in file_formats}
def organize_files():
"""Organize files in current directory by type"""
# Organize known file types
for entry in os.scandir():
if entry.is_dir():
continue
file_path = Path(entry)
file_format = file_path.suffix.lower()
if file_format in FILE_FORMATS:
directory_path = Path(FILE_FORMATS[file_format])
directory_path.mkdir(exist_ok=True)
file_path.rename(directory_path.joinpath(file_path.name))
# Move remaining files to OTHER-FILES
other_files_path = Path("OTHER-FILES")
other_files_path.mkdir(exist_ok=True)
for entry in os.scandir():
if not entry.is_dir():
file_path = Path(entry)
file_path.rename(other_files_path / file_path.name)
# Remove empty directories
for entry in os.scandir():
if entry.is_dir():
try:
os.rmdir(entry.path)
except OSError:
pass
if __name__ == "__main__":
print("Starting file organization...")
organize_files()
print("File organization completed!")
How It Works
The script follows these steps:
-
Scan files − Uses
os.scandir()to iterate through current directory - Check extensions − Matches file extensions against the predefined categories
-
Create folders − Creates category folders using
mkdir(exist_ok=True) -
Move files − Uses
Path.rename()to move files to appropriate folders - Handle unknowns − Moves unrecognized files to "OTHER-FILES" folder
- Clean up − Removes empty directories
Usage Instructions
To use this script:
- Navigate to the directory you want to organize
- Save the script as
file_organizer.py - Run with:
python file_organizer.py
Warning: Always backup important files before running the script, as it modifies directory structure.
Conclusion
This file organizer script automatically sorts files by type into categorized folders. It's useful for cleaning cluttered directories and maintaining organized file structures with minimal manual effort.
