File Organizer
This utility declutters a directory by moving files into subfolders based on their file extensions. It uses pathlib for robust path handling and shutil for moving files.
Modules Used:
- shutil: To move files from one location to another.
- pathlib: To traverse directories, extract extensions, and create folders.
- argparse: To handle command-line arguments.
The Code
Save this as organize.py.
import argparse
import shutil
from pathlib import Path
def organize_files(directory):
path = Path(directory)
if not path.exists():
print(f"Error: Directory '{directory}' not found.")
return
# Get all files in the directory (excluding directories)
files = [f for f in path.iterdir() if f.is_file()]
if not files:
print("No files found to organize.")
return
print(f"Organizing {len(files)} files in '{directory}'...")
for file in files:
# Skip hidden files (like .DS_Store or .gitignore)
if file.name.startswith('.'):
continue
# Get extension (without dot), default to 'no_extension' if missing
ext = file.suffix.lower().lstrip('.')
if not ext:
ext = 'no_extension'
# Create target folder path (e.g., ./downloads/pdf)
target_folder = path / ext
# Create the folder if it doesn't exist
target_folder.mkdir(exist_ok=True)
# Move file
try:
destination = target_folder / file.name
shutil.move(str(file), str(destination))
print(f"Moved: {file.name} -> {ext}/")
except Exception as e:
print(f"Error moving {file.name}: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="File Organizer based on extension")
parser.add_argument("directory", help="Directory to organize")
args = parser.parse_args()
organize_files(args.directory)
Usage
# Organize the Downloads folder
python organize.py ~/Downloads
# Organize the current directory
python organize.py .