The user wants a Python CLI tool to rename and organize files based on metadata. This is a useful utility that can:
- Read metadata from various file types (images, documents, videos, audio)
- Rename files based on patterns using metadata
- Organize files into folders based on metadata (like date, type, etc.)
I'll create a comprehensive CLI tool with the following features:
- Support for multiple file types (images, videos, audio, documents)
- Extract metadata like creation date, modification date, EXIF data for images
- Pattern-based renaming with templates
- Organize files into folder structures based on metadata
- Preview mode before making changes
- Undo capability
- Logging
I'll use:
click for CLI (it's popular and clean)
Pillow for image metadata (EXIF)
datetime for date handling
pathlib for file operations
tinydb or just JSON for storing rename history for undo
rich for beautiful CLI output
Let me create a complete, standalone tool:
#!/usr/bin/env python3
"""
File Organizer CLI Tool
Rename and organize files based on their metadata.
"""
import click
import json
import shutil
import hashlib
from pathlib import Path
from datetime import datetime
from typing import Dict, Optional, List, Tuple
from dataclasses import dataclass, asdict
import re
# For image metadata
try:
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS, GPSTAGS
PILLOW_AVAILABLE = True
except ImportError:
PILLOW_AVAILABLE = False
# For rich output
try:
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.panel import Panel
RICH_AVAILABLE = True
except ImportError:
RICH_AVAILABLE = False
# For audio metadata
try:
from tinytag import TinyTag
TINYTAG_AVAILABLE = True
except ImportError:
TINYTAG_AVAILABLE = False
Actually, let me make this more comprehensive and self-contained. I'll create a full-featured tool that works without too many dependencies by falling back gracefully.
Let me design the full solution:
- Core metadata extraction
- Pattern-based renaming
- File organization into folders
- Preview and dry-run modes
- Undo functionality
- Rich CLI interface
I'll make it a single file that can be run directly.
File Organizer CLI Tool
A powerful Python CLI tool to rename and organize files based on their metadata (EXIF, ID3, dates, etc.).
Installation
# Install required dependencies
pip install click rich pillow tinytab
Complete Code
#!/usr/bin/env python3
"""
File Organizer CLI Tool
Rename and organize files based on their metadata.
Supports images (EXIF), audio (ID3), videos, and documents.
"""
import os
import sys
import json
import shutil
import hashlib
import re
from pathlib import Path
from datetime import datetime
from typing import Dict, Optional, List, Any, Tuple
from dataclasses import dataclass, asdict, field
from enum import Enum
import click
# Optional dependencies with graceful fallback
try:
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS
PILLOW_AVAILABLE = True
except ImportError:
PILLOW_AVAILABLE = False
try:
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.panel import Panel
from rich.tree import Tree
RICH_AVAILABLE = True
console = Console()
except ImportError:
RICH_AVAILABLE = False
console = None
try:
from tinytag import TinyTag
TINYTAG_AVAILABLE = True
except ImportError:
TINYTAG_AVAILABLE = False
# ============================================================================
# Data Classes and Enums
# ============================================================================
class FileCategory(Enum):
IMAGE = "image"
VIDEO = "video"
AUDIO = "audio"
DOCUMENT = "document"
ARCHIVE = "archive"
CODE = "code"
OTHER = "other"
@dataclass
class FileMetadata:
"""Container for extracted file metadata"""
path: Path
size: int
created_date: datetime
modified_date: datetime
category: FileCategory
extension: str
mime_type: str = ""
# Image specific
exif_date: Optional[datetime] = None
camera_make: str = ""
camera_model: str = ""
width: int = 0
height: int = 0
# Audio specific
artist: str = ""
album: str = ""
title: str = ""
track_number: int = 0
duration: int = 0
genre: str = ""
year: int = 0
# Document specific
author: str = ""
def to_dict(self) -> Dict:
"""Convert to dictionary for JSON serialization"""
d = asdict(self)
d['path'] = str(self.path)
d['created_date'] = self.created_date.isoformat()
d['modified_date'] = self.modified_date.isoformat()
d['category'] = self.category.value
if self.exif_date:
d['exif_date'] = self.exif_date.isoformat()
return d
@dataclass
class RenameOperation:
"""Represents a single rename/organize operation"""
original_path: Path
new_path: Path
metadata: FileMetadata
timestamp: datetime = field(default_factory=datetime.now)
completed: bool = False
def to_dict(self) -> Dict:
return {
'original_path': str(self.original_path),
'new_path': str(self.new_path),
'metadata': self.metadata.to_dict(),
'timestamp': self.timestamp.isoformat(),
'completed': self.completed
}
# ============================================================================
# File Type Detection
# ============================================================================
EXTENSION_MAP = {
# Images
'.jpg': FileCategory.IMAGE, '.jpeg': FileCategory.IMAGE,
'.png': FileCategory.IMAGE, '.gif': FileCategory.IMAGE,
'.bmp': FileCategory.IMAGE, '.tiff': FileCategory.IMAGE,
'.tif': FileCategory.IMAGE, '.webp': FileCategory.IMAGE,
'.raw': FileCategory.IMAGE, '.heic': FileCategory.IMAGE,
'.cr2': FileCategory.IMAGE, '.nef': FileCategory.IMAGE,
'.svg': FileCategory.IMAGE, '.ico': FileCategory.IMAGE,
# Videos
'.mp4': FileCategory.VIDEO, '.avi': FileCategory.VIDEO,
'.mkv': FileCategory.VIDEO, '.mov': FileCategory.VIDEO,
'.wmv': FileCategory.VIDEO, '.flv': FileCategory.VIDEO,
'.webm': FileCategory.VIDEO, '.m4v': FileCategory.VIDEO,
'.mpeg': FileCategory.VIDEO, '.mpg': FileCategory.VIDEO,
'.3gp': FileCategory.VIDEO,
# Audio
'.mp3': FileCategory.AUDIO, '.wav': FileCategory.AUDIO,
'.flac': FileCategory.AUDIO, '.aac': FileCategory.AUDIO,
'.ogg': FileCategory.AUDIO, '.wma': FileCategory.AUDIO,
'.m4a': FileCategory.AUDIO, '.opus': FileCategory.AUDIO,
'.aiff': FileCategory.AUDIO, '.ape': FileCategory.AUDIO,
# Documents
'.pdf': FileCategory.DOCUMENT, '.doc': FileCategory.DOCUMENT,
'.docx': FileCategory.DOCUMENT, '.xls': FileCategory.DOCUMENT,
'.xlsx': FileCategory.DOCUMENT, '.ppt': FileCategory.DOCUMENT,
'.pptx': FileCategory.DOCUMENT, '.txt': FileCategory.DOCUMENT,
'.rtf': FileCategory.DOCUMENT, '.odt': FileCategory.DOCUMENT,
'.ods': FileCategory.DOCUMENT, '.odp': FileCategory.DOCUMENT,
'.md': FileCategory.DOCUMENT, '.csv': FileCategory.DOCUMENT,
# Archives
'.zip': FileCategory.ARCHIVE, '.rar': FileCategory.ARCHIVE,
'.7z': FileCategory.ARCHIVE, '.tar': FileCategory.ARCHIVE,
'.gz': FileCategory.ARCHIVE, '.bz2': FileCategory.ARCHIVE,
# Code
'.py': FileCategory.CODE, '.js': FileCategory.CODE,
'.ts': FileCategory.CODE, '.java': FileCategory.CODE,
'.cpp': FileCategory.CODE, '.c': FileCategory.CODE,
'.h': FileCategory.CODE, '.hpp': FileCategory.CODE,
'.cs': FileCategory.CODE, '.go': FileCategory.CODE,
'.rs': FileCategory.CODE, '.rb': FileCategory.CODE,
'.php': FileCategory.CODE, '.swift': FileCategory.CODE,
'.kt': FileCategory.CODE, '.scala': FileCategory.CODE,
'.html': FileCategory.CODE, '.css': FileCategory.CODE,
'.json': FileCategory.CODE, '.xml': FileCategory.CODE,
'.yaml': FileCategory.CODE, '.yml': FileCategory.CODE,
'.sql': FileCategory.CODE, '.sh': FileCategory.CODE,
}
# ============================================================================
# Metadata Extractor
# ============================================================================
class MetadataExtractor:
"""Extract metadata from various file types"""
@staticmethod
def get_category(file_path: Path) -> FileCategory:
"""Determine file category based on extension"""
ext = file_path.suffix.lower()
return EXTENSION_MAP.get(ext, FileCategory.OTHER)
@staticmethod
def get_file_dates(file_path: Path) -> Tuple[datetime, datetime]:
"""Get file creation and modification dates"""
stat = file_path.stat()
# Creation time (platform dependent)
try:
created = datetime.fromtimestamp(stat.st_ctime)
except:
created = datetime.now()
modified = datetime.fromtimestamp(stat.st_mtime)
return created, modified
@staticmethod
def extract_exif(image_path: Path) -> Dict[str, Any]:
"""Extract EXIF data from image files"""
if not PILLOW_AVAILABLE:
return {}
exif_data = {}
try:
with Image.open(image_path) as img:
exif_info = img._getexif()
if exif_info:
for tag, value in exif_info.items():
tag_name = TAGS.get(tag, tag)
exif_data[tag_name] = value
# Get dimensions
exif_data['width'] = img.width
exif_data['height'] = img.height
# Try to get DateTimeOriginal
if 'DateTimeOriginal' in exif_data:
try:
date_str = exif_data['DateTimeOriginal']
exif_data['exif_date'] = datetime.strptime(
date_str, '%Y:%m:%d %H:%M:%S'
)
except:
pass
# Camera info
exif_data['make'] = exif_data.get('Make', '')
exif_data['model'] = exif_data.get('Model', '')
except Exception as e:
pass
return exif_data
@staticmethod
def extract_audio_metadata(file_path: Path) -> Dict[str, Any]:
"""Extract metadata from audio files"""
if not TINYTAG_AVAILABLE:
return {}
audio_data = {}
try:
tag = TinyTag.get(str(file_path))
audio_data['title'] = tag.title or ''
audio_data['artist'] = tag.artist or ''
audio_data['album'] = tag.album or ''
audio_data['year'] = int(tag.year) if tag.year else 0
audio_data['track_number'] = int(tag.track) if tag.track else 0
audio_data['genre'] = tag.genre or ''
audio_data['duration'] = int(tag.duration) if tag.duration else 0
except Exception as e:
pass
return audio_data
@classmethod
def extract(cls, file_path: Path) -> FileMetadata:
"""Extract all available metadata from a file"""
category = cls.get_category(file_path)
created, modified = cls.get_file_dates(file_path)
metadata = FileMetadata(
path=file_path,
size=file_path.stat().st_size,
created_date=created,
modified_date=modified,
category=category,
extension=file_path.suffix.lower()
)
# Extract category-specific metadata
if category == FileCategory.IMAGE:
exif = cls.extract_exif(file_path)
if exif:
metadata.exif_date = exif.get('exif_date')
metadata.camera_make = exif.get('make', '')
metadata.camera_model = exif.get('model', '')
metadata.width = exif.get('width', 0)
metadata.height = exif.get('height', 0)
elif category == FileCategory.AUDIO:
audio = cls.extract_audio_metadata(file_path)
if audio:
metadata.title = audio.get('title', '')
metadata.artist = audio.get('artist', '')
metadata.album = audio.get('album', '')
metadata.year = audio.get('year', 0)
metadata.track_number = audio.get('track_number', 0)
metadata.genre = audio.get('genre', '')
metadata.duration = audio.get('duration', 0)
return metadata
# ============================================================================
# Pattern Processor
# ============================================================================
class PatternProcessor:
"""Process naming patterns with metadata placeholders"""
# Available placeholders
PATTERNS = {
# Date patterns
'{year}': lambda m: str(m.created_date.year),
'{month}': lambda m: f"{m.created_date.month:02d}",
'{day}': lambda m: f"{m.created_date.day:02d}",
'{hour}': lambda m: f"{m.created_date.hour:02d}",
'{minute}': lambda m: f"{m.created_date.minute:02d}",
'{second}': lambda m: f"{m.created_date.second:02d}",
'{date}': lambda m: m.created_date.strftime('%Y-%m-%d'),
'{datetime}': lambda m: m.created_date.strftime('%Y-%m-%d_%H-%M-%S'),
'{exif_year}': lambda m: str(m.exif_date.year) if m.exif_date else '',
'{exif_month}': lambda m: f"{m.exif_date.month:02d}" if m.exif_date else '',
'{exif_day}': lambda m: f"{m.exif_date.day:02d}" if m.exif_date else '',
'{exif_date}': lambda m: m.exif_date.strftime('%Y-%m-%d') if m.exif_date else '',
'{exif_datetime}': lambda m: m.exif_date.strftime('%Y-%m-%d_%H-%M-%S') if m.exif_date else '',
# File properties
'{ext}': lambda m: m.extension,
'{category}': lambda m: m.category.value,
'{size}': lambda m: str(m.size),
'{size_kb}': lambda m: str(m.size // 1024),
'{size_mb}': lambda m: f"{m.size / (1024*1024):.2f}",
# Image specific
'{camera}': lambda m: f"{m.camera_make}_{m.camera_model}".strip('_'),
'{make}': lambda m: m.camera_make,
'{model}': lambda m: m.camera_model,
'{width}': lambda m: str(m.width),
'{height}': lambda m: str(m.height),
'{resolution}': lambda m: f"{m.width}x{m.height}" if m.width and m.height else '',
# Audio specific
'{artist}': lambda m: cls._sanitize(m.artist),
'{album}': lambda m: cls._sanitize(m.album),
'{title}': lambda m: cls._sanitize(m.title),
'{track}': lambda m: f"{m.track_number:02d}" if m.track_number else '',
'{genre}': lambda m: cls._sanitize(m.genre),
'{audio_year}': lambda m: str(m.year) if m.year else '',
}
@classmethod
def _sanitize(cls, text: str) -> str:
"""Sanitize text for use in filenames"""
if not text:
return ''
# Remove invalid filename characters
sanitized = re.sub(r'[<>:"/\\|?*]', '', text)
# Replace spaces with underscores or keep as is
sanitized = sanitized.strip()
return sanitized
@classmethod
def process(cls, pattern: str, metadata: FileMetadata) -> str:
"""Process a pattern string with metadata"""
result = pattern
for placeholder, getter in cls.PATTERNS.items():
if placeholder in result:
value = getter(metadata)
result = result.replace(placeholder, value)
return result
@classmethod
def generate_filename(cls, pattern: str, metadata: FileMetadata,
keep_original: bool = False) -> str:
"""Generate new filename from pattern"""
processed = cls.process(pattern, metadata)
# Ensure we have an extension
if not processed.endswith(metadata.extension):
if not processed.endswith('.'):
processed += metadata.extension if metadata.extension else ''
# Handle empty results
if not processed or processed == metadata.extension:
return metadata.path.name
return processed
# ============================================================================
# File Organizer
# ============================================================================
class FileOrganizer:
"""Main class for organizing and renaming files"""
HISTORY_FILE = ".file_organizer_history.json"
def __init__(self, dry_run: bool = False, verbose: bool = False):
self.dry_run = dry_run
self.verbose = verbose
self.operations: List[RenameOperation] = []
def _print(self, message: str, style: str = None):
"""Print message with optional styling"""
if RICH_AVAILABLE and console:
if style:
console.print(message, style=style)
else:
console.print(message)
else:
print(message)
def scan_directory(self, directory: Path, recursive: bool = True,
categories: List[FileCategory] = None,
extensions: List[str] = None) -> List[FileMetadata]:
"""Scan directory for files and extract metadata"""
files = []
pattern = "**/*" if recursive else "*"
for file_path in directory.glob(pattern):
if not file_path.is_file():
continue
metadata = MetadataExtractor.extract(file_path)
# Filter by category
if categories and metadata.category not in categories:
continue
# Filter by extension
if extensions and metadata.extension.lower() not in [e.lower() for e in extensions]:
continue
files.append(metadata)
return files
def generate_new_path(self, metadata: FileMetadata,
rename_pattern: str = None,
organize_pattern: str = None,
dest_dir: Path = None) -> Path:
"""Generate new path for a file based on patterns"""
# Start with destination directory or original parent
base_dir = dest_dir or metadata.path.parent
# Apply organize pattern for subdirectory structure
if organize_pattern:
subdir = PatternProcessor.process(organize_pattern, metadata)
if subdir:
base_dir = base_dir / subdir
# Generate filename
if rename_pattern:
new_name = PatternProcessor.generate_filename(rename_pattern, metadata)
else:
new_name = metadata.path.name
return base_dir / new_name
def preview_operations(self, operations: List[RenameOperation]):
"""Show preview of all operations"""
if RICH_AVAILABLE and console:
table = Table(title="Preview Operations", show_header=True, header_style="bold magenta")
table.add_column("Original", style="cyan", width=40)
table.add_column("New", style="green", width=40)
table.add_column("Category", style="yellow", width=10)
for op in operations:
table.add_row(
str(op.original_path.relative_to(op.original_path.parents[-2])),
str(op.new_path.relative_to(op.new_path.parents[-2])) if op.new_path.parents else str(op.new_path),
op.metadata.category.value
)
console.print(table)
else:
print(f"\n{'Original':<50} {'New':<50} {'Category':<10}")
print("-" * 110)
for op in operations:
print(f"{str(op.original_path):<50} {str(op.new_path):<50} {op.metadata.category.value:<10}")
def execute_operations(self, operations: List[RenameOperation],
copy: bool = False) -> Tuple[int, int]:
"""Execute all rename/move operations"""
success_count = 0
fail_count = 0
iterator = operations
if RICH_AVAILABLE:
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
console=console
) as progress:
task = progress.add_task("Processing files...", total=len(operations))
for op in progress.track(operations, task_id=task):
if self._execute_single(op, copy):
success_count += 1
else:
fail_count += 1
else:
for op in operations:
print(f"Processing: {op.original_path.name}...")
if self._execute_single(op, copy):
success_count += 1
else:
fail_count += 1
return success_count, fail_count
def _execute_single(self, op: RenameOperation, copy: bool = False) -> bool:
"""Execute a single operation"""
try:
# Create destination directory if needed
op.new_path.parent.mkdir(parents=True, exist_ok=True)
if self.dry_run:
self._print(f" [DRY RUN] Would {'copy' if copy else 'move'}: {op.original_path} -> {op.new_path}", "yellow")
return True
if copy:
shutil.copy2(op.original_path, op.new_path)
else:
shutil.move(str(op.original_path), op.new_path)
op.completed = True
return True
except Exception as e:
self._print(f" Error processing {op.original_path}: {e}", "red")
return False
def save_history(self, operations: List[RenameOperation], history_file: Path = None):
"""Save operations to history file for potential undo"""
history_path = history_file or Path(self.HISTORY_FILE)
history_data = []
if history_path.exists():
with open(history_path, 'r') as f:
history_data = json.load(f)
history_data.extend([op.to_dict() for op in operations])
with open(history_path, 'w') as f:
json.dump(history_data, f, indent=2)
def undo_last(self, history_file: Path = None, count: int = 1):
"""Undo last N operations from history"""
history_path = history_file or Path(self.HISTORY_FILE)
if not history_path.exists():
self._print("No history file found.", "red")
return
with open(history_path, 'r') as f:
history_data = json.load(f)
if not history_data:
self._print("No operations to undo.", "yellow")
return
# Get last N operations
to_undo = history_data[-count:]
history_data = history_data[:-count]
for op_data in reversed(to_undo):
original = Path(op_data['original_path'])
new_path = Path(op_data['new_path'])
if new_path.exists():
try:
shutil.move(str(new_path), original)
self._print(f"Restored: {new_path} -> {original}", "green")
except Exception as e:
self._print(f"Failed to restore {new_path}: {e}", "red")
# Save updated history
with open(history_path, 'w') as f:
json.dump(history_data, f, indent=2)
def show_statistics(self, files: List[FileMetadata]):
"""Display statistics about scanned files"""
if RICH_AVAILABLE and console:
# Category stats
category_counts = {}
total_size = 0
for f in files:
cat = f.category.value
category_counts[cat] = category_counts.get(cat, 0) + 1
total_size += f.size
table = Table(title="File Statistics", show_header=True)
table.add_column("Category", style="cyan")
table.add_column("Count", style="green", justify="right")
table.add_column("Size", style="yellow", justify="right")
for cat, count in sorted(category_counts.items()):
cat_size = sum(f.size for f in files if f.category.value == cat)
table.add_row(cat, str(count), self._format_size(cat_size))
console.print(table)
console.print(f"\nTotal: {len(files)} files, {self._format_size(total_size)}")
else:
category_counts = {}
total_size = 0
for f in files:
cat = f.category.value
category_counts[cat] = category_counts.get(cat, 0) + 1
total_size += f.size
print("\n=== File Statistics ===")
for cat, count in sorted(category_counts.items()):
cat_size = sum(f.size for f in files if f.category.value == cat)
print(f"{cat:<15} {count:>5} files {self._format_size(cat_size):>15}")
print(f"\nTotal: {len(files)} files, {self._format_size(total_size)}")
def _format_size(self, size: int) -> str:
"""Format file size in human-readable format"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} PB"
# ============================================================================
# CLI Interface
# ============================================================================
def print_banner():
"""Print CLI banner"""
if RICH_AVAILABLE and console:
console.print(Panel.fit(
"[bold blue]File Organizer[/bold blue] [green]v1.0.0[/green]\n"
"[dim]Rename and organize files based on metadata[/dim]",
border_style="blue"
))
else:
print("\n" + "="*50)
print("File Organizer v1.0.0")
print("Rename and organize files based on metadata")
print("="*50 + "\n")
@click.group()
@click.version_option(version='1.0.0')
def cli():
"""File Organizer - Rename and organize files based on metadata"""
print_banner()
@cli.command()
@click.argument('source', type=click.Path(exists=True))
@click.option('--rename', '-r', help='Rename pattern (e.g., "{date}_{camera}{ext}")')
@click.option('--organize', '-o', help='Organization pattern (e.g., "{category}/{year}/{month}")')
@click.option('--destination', '-d', type=click.Path(), help='Destination directory')
@click.option('--recursive/--no-recursive', default=True, help='Scan directories recursively')
@click.option('--copy', '-c', is_flag=True, help='Copy files instead of moving')
@click.option('--dry-run', '-n', is_flag=True, help='Preview without making changes')
@click.option('--category', '-t', multiple=True,
type=click.Choice(['image', 'video', 'audio', 'document', 'archive', 'code', 'other']),
help='Filter by file category (can specify multiple)')
@click.option('--extension', '-e', multiple=True, help='Filter by extension (e.g., -e .jpg -e .png)')
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
def process(source, rename, organize, destination, recursive, copy, dry_run,
category, extension, verbose):
"""Process and organize files from SOURCE directory."""
organizer = FileOrganizer(dry_run=dry_run, verbose=verbose)
source_path = Path(source).resolve()
dest_path = Path(destination).resolve() if destination else None
# Convert category strings to enums
categories = None
if category:
categories = [FileCategory(c) for c in category]
# Scan files
organizer._print(f"\nScanning: {source_path}", "cyan")
files = organizer.scan_directory(
source_path,
recursive=recursive,
categories=categories,
extensions=list(extension) if extension else None
)
if not files:
organizer._print("No files found matching criteria.", "yellow")
return
# Show statistics
organizer.show_statistics(files)
# Generate operations
operations = []
for metadata in files:
new_path = organizer.generate_new_path(
metadata,
rename_pattern=rename,
organize_pattern=organize,
dest_dir=dest_path
)
# Skip if no change
if new_path == metadata.path:
if verbose:
organizer._print(f"Skipping (no change): {metadata.path.name}", "dim")
continue
operations.append(RenameOperation(
original_path=metadata.path,
new_path=new_path,
metadata=metadata
))
if not operations:
organizer._print("\nNo changes needed.", "green")
return
# Preview operations
organizer._print(f"\n[bold]{len(operations)} operations to perform:[/bold]")
organizer.preview_operations(operations)
# Confirm execution
if not dry_run:
if not click.confirm("\nProceed with changes?"):
organizer._print("Operation cancelled.", "yellow")
return
# Execute operations
success, fail = organizer.execute_operations(operations, copy=copy)
organizer._print(f"\n[bold]Results:[/bold] {success} successful, {fail} failed",
"green" if fail == 0 else "yellow")
# Save history for undo
if not dry_run and success > 0:
organizer.save_history(operations)
organizer._print("History saved. Use 'undo' command to revert if needed.", "dim")
@cli.command()
@click.argument('source', type=click.Path(exists=True))
@click.option('--recursive/--no-recursive', default=True)
@click.option('--category', '-t', multiple=True,
type=click.Choice(['image', 'video', 'audio', 'document', 'archive', 'code', 'other']))
def scan(source, recursive, category):
"""Scan and display file information without making changes."""
organizer = FileOrganizer(dry_run=True)
source_path = Path(source).resolve()
categories = [FileCategory(c) for c in category] if category else None
files = organizer.scan_directory(
source_path,
recursive=recursive,
categories=categories
)
organizer.show_statistics(files)
if RICH_AVAILABLE and console:
console.print("\n[bold]Sample files:[/bold]")
table = Table(show_header=True)
table.add_column("File", style="cyan", width=30)
table.add_column("Category", style="green", width=10)
table.add_column("Size", style="yellow", width=10)
table.add_column("Modified", style="magenta", width=20)
for f in files[:20]: # Show first 20
table.add_row(
f.path.name[:30],
f.category.value,
organizer._format_size(f.size),
f.modified_date.strftime('%Y-%m-%d %H:%M:%S')
)
console.print(table)
if len(files) > 20:
console.print(f"... and {len(files) - 20} more files")
@cli.command('list-patterns')
def list_patterns():
"""List all available pattern placeholders."""
if RICH_AVAILABLE and console:
table = Table(title="Available Pattern Placeholders")
table.add_column("Placeholder", style="cyan")
table.add_column("Description", style="green")
table.add_column("Example", style="yellow")
else:
print("\nAvailable Pattern Placeholders:")
print("-" * 60)
patterns_info = [
("{year}", "Year from file date", "2024"),
("{month}", "Month (01-12)", "03"),
("{day}", "Day (01-31)", "15"),
("{date}", "Full date (YYYY-MM-DD)", "2024-03-15"),
("{datetime}", "Full datetime", "2024-03-15_14-30-00"),
("{exif_year}", "Year from EXIF data", "2024"),
("{exif_date}", "Date from EXIF", "2024-03-15"),
("{ext}", "File extension", ".jpg"),
("{category}", "File category", "image"),
("{camera}", "Camera make and model", "Canon_EOS_R5"),
("{make}", "Camera make", "Canon"),
("{model}", "Camera model", "EOS R5"),
("{resolution}", "Image resolution", "8192x5464"),
("{artist}", "Audio artist", "The Beatles"),
("{album}", "Audio album", "Abbey Road"),
("{title}", "Audio title", "Come Together"),
("{track}", "Track number", "01"),
("{genre}", "Audio genre", "Rock"),
("{audio_year}", "Audio release year", "1969"),
("{size_kb}", "File size in KB", "2048"),
("{size_mb}", "File size in MB", "2.5"),
]
for placeholder, desc, example in patterns_info:
if RICH_AVAILABLE and console:
table.add_row(placeholder, desc, example)
else:
print(f"{placeholder:<20} {desc:<30} {example}")
if RICH_AVAILABLE and console:
console.print(table)
console.print("\n[dim]Example patterns:[/dim]")
console.print(" Rename: {date}_{camera}{ext}")
console.print(" Organize: {category}/{year}/{month}")
console.print(" Full: Photos/{year}/{month}/{date}_{time}{ext}")
@cli.command()
@click.option('--count', '-c', default=1, help='Number of operations to undo')
@click.option('--history-file', type=click.Path(), help='Custom history file path')
def undo(count, history_file):
"""Undo last file operations."""
organizer = FileOrganizer()
history_path = Path(history_file) if history_file else None
organizer._print(f"Undoing last {count} operation(s)...", "cyan")
organizer.undo_last(history_path, count)
@cli.command()
def info():
"""Display information about available features and dependencies."""
organizer = FileOrganizer()
if RICH_AVAILABLE and console:
console.print(Panel("[bold]System Information[/bold]", border_style="blue"))
table = Table(show_header=True)
table.add_column("Feature", style="cyan")
table.add_column("Status", style="green")
table.add_column("Description", style="dim")
else:
print("\nSystem Information:")
print("-" * 60)
features = [
("Rich Output", RICH_AVAILABLE, "Enhanced terminal display"),
("PIL/Pillow", PILLOW_AVAILABLE, "Image metadata (EXIF) extraction"),
("TinyTag", TINYTAG_AVAILABLE, "Audio metadata (ID3) extraction"),
]
for name, available, desc in features:
status = "✓ Installed" if available else "✗ Not installed"
if RICH_AVAILABLE and console:
status_style = "green" if available else "red"
table.add_row(name, f"[{status_style}]{status}[/{status_style}]", desc)
else:
print(f"{name:<15} {status:<15} {desc}")
if RICH_AVAILABLE and console:
console.print(table)
console.print("\n[dim]Install missing dependencies with:[/dim]")
console.print("[dim] pip install pillow tinytag rich[/dim]")
# ============================================================================
# Entry Point
# ============================================================================
if __name__ == '__main__':
cli()
Usage Examples
Basic Commands
# Scan a directory and see file statistics
python file_organizer.py scan ~/Downloads
# Preview rename operations (dry run)
python file_organizer.py process ~/Photos --rename "{date}_{camera}{ext}" --dry-run
# Organize photos by date
python file_organizer.py process ~/Photos --organize "{category}/{year}/{month}" --destination ~/Organized
# Rename and organize music files
python file_organizer.py process ~/Music --rename "{track}_{title}{ext}" --organize "{artist}/{album}"
# Copy files instead of moving
python file_organizer.py process ~/Documents --organize "{category}/{year}" --copy
Pattern Examples
# List all available patterns
python file_organizer.py list-patterns
# Rename photos with EXIF date and camera
python file_organizer.py process ~/Photos --rename "{exif_date}_{camera}{ext}"
# Organize by category and year
python file_organizer.py process ~/Downloads --organize "{category}/{year}"
# Complex organization pattern
python file_organizer.py process ~/Files --organize "{category}/{year}/{month}" --rename "{datetime}_{category}{ext}"
Filtering Options
# Process only images
python file_organizer.py process ~/Mixed --category image
# Process only specific extensions
python file_organizer.py process ~/Files --extension .jpg --extension .png
# Combine filters
python file_organizer.py process ~/Media --category video --extension .mp4 --organize "{year}"
Undo Operations
# Undo last operation
python file_organizer.py undo
# Undo last 5 operations
python file_organizer.py undo --count 5
Available Pattern Placeholders
| Placeholder | Description | Example |
|---|
{year}, {month}, {day} | Date components | 2024, 03, 15 |
{date}, {datetime} | Full date/datetime | 2024-03-15 |
{exif_date} | Date from EXIF | 2024-03-15 |
{camera}, {make}, {model} | Camera info | Canon_EOS_R5 |
{artist}, {album}, {title} | Audio metadata | The Beatles |
{track}, {genre}, {audio_year} | Audio details | 01, Rock, 1969 |
{category} | File category | image, audio |
{ext} | File extension | .jpg |
{size_kb}, {size_mb} | File size | 2048, 2.5 |
Features
- Metadata Extraction: EXIF for images, ID3 for audio files
- Flexible Patterns: Rich pattern system for renaming and organization
- Preview Mode: Dry-run to see changes before applying
- Undo Support: Revert operations using history
- File Filtering: By category or extension
- Copy/Move Options: Choose between copying or moving files
- Rich CLI Output: Beautiful tables and progress indicators
- Recursive Scanning: Process nested directories