Create a Python CLI tool to rename and organize files based on metadata.
- User
Create a Python CLI tool to rename and organize files based on metadata.
Assistant
Define the Scope
I'm currently focused on defining the initial scope of this Python CLI tool. I've pinpointed the central goal: renaming and organizing files using their metadata. I'm also identifying its key features, namely a user-friendly CLI interface. It's a foundational step, but I feel I have a solid understanding of the desired functionality.
Expanding the Features
Now, I'm thinking about the nitty-gritty features. I've sketched out how the tool will traverse directories, extract metadata with libraries, and use a templating system for new filenames. I'm considering options for conflict resolution, such as skipping, overwriting, or renaming. Dry-run functionality is essential for safety. I'm also now settled on
argparsefor the CLI for the time being, to keep it lightweight.Developing the Structure
My current focus is crafting the program's structural elements. I've chosen the required imports, including
argparsefor the CLI. I am now working on the metadata extraction functions, usingPillowfor images andmutagenfor audio, although a native fallback will be provided. The core logic components are taking shape too. I have settled on a time-based organization strategy.Designing the Pattern System
I'm now implementing the pattern system. I'm focusing on user-friendly filename and directory structures, like
2023-10-01_Holiday.jpg. I've settled on custom placeholder tokens, such as{year},{month},{ext}, and{original_name}, avoiding Python's f-string formatting for CLI safety. This will enable flexible and descriptive naming options for users. I am also working on time/date format extraction in native Python.Incorporating Advanced Date Handling
I've just added support for
strftimecodes, making the date handling even more flexible. I'm focusing on pre-calculating those values to simplify things. Also, I'm now choosing betweenshutil.copy2for metadata preservation orshutil.movefor straightforward renaming. I'm also implementing the optionalPILpackage to automatically pull Exif data from images, with a fallback if the library isn't available. I've begun to handle filename conflicts by appending incremental counters to filenames, ensuring all files are handled. Finally, I'm organizing the code into an actual structure, including a shebang and helper functions, and am thinking about the code for each supported filetype.Finalizing Output and Structure
I'm now integrating the ability to handle EXIF data from images to minimize external dependencies, offering enhanced utility. I'm also adding color-coded CLI output using ANSI escape codes for improved readability. The documentation is taking shape, including a concise introduction, prerequisites, well-commented code, explanations of key components, and practical usage examples. I've also incorporated the distinction between copying and moving files, making copying the default with a
--moveflag for more advanced users.Here is a complete, robust Python CLI tool designed to rename and organize files.
Key Features
- Smart Metadata Extraction: Prioritizes EXIF data (for photos) and falls back to file creation dates.
- Flexible Templating: Allows you to define the folder structure and naming convention using placeholders (e.g.,
{year},{month},{original_name}). - Dry Run: A safety mode to preview changes without actually moving files.
- Conflict Handling: Automatically adds numbers (e.g.,
_1,_2) if a file with the same name exists.
Prerequisites
This script uses the standard library for most tasks, but for Image EXIF data support, you need Pillow.
pip install PillowThe Python Script (
organize.py)Save the following code into a file named
organize.py.import os import shutil import argparse import datetime from pathlib import Path import sys # Try importing Pillow for Image EXIF data, handle gracefully if missing try: from PIL import Image, UnidentifiedImageError from PIL.ExifTags import TAGS HAS_PILLOW = True except ImportError: HAS_PILLOW = False # ANSI Color codes for CLI output GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' RESET = '\033[0m' def get_exif_date(file_path): """Attempts to retrieve the original date taken from image EXIF data.""" if not HAS_PILLOW: return None try: with Image.open(file_path) as img: exif_data = img._getexif() if not exif_data: return None for tag, value in exif_data.items(): decoded = TAGS.get(tag, tag) if decoded == "DateTimeOriginal": # Format usually: "YYYY:MM:DD HH:MM:SS" return datetime.datetime.strptime(value, "%Y:%m:%d %H:%M:%S") except (UnidentifiedImageError, ValueError, AttributeError, Exception): return None return None def get_date_metadata(file_path): """ Returns a datetime object. Priority: EXIF Date -> File Creation Date -> File Modified Date """ # 1. Try EXIF (if image) exif_date = get_exif_date(file_path) if exif_date: return exif_date # 2. OS Creation/Modification time stat = os.stat(file_path) try: # creation time (Windows) or metadata change time (Unix) timestamp = stat.st_birthtime except AttributeError: # Fallback for Unix where birthtime isn't available timestamp = stat.st_mtime return datetime.datetime.fromtimestamp(timestamp) def get_unique_path(destination): """ If file exists, append _1, _2, etc. e.g., image.jpg -> image_1.jpg """ if not destination.exists(): return destination path = Path(destination) name = path.stem suffix = path.suffix parent = path.parent counter = 1 while True: new_path = parent / f"{name}_{counter}{suffix}" if not new_path.exists(): return new_path counter += 1 def organize_files(args): src_dir = Path(args.source) dest_base = Path(args.destination) if not src_dir.exists(): print(f"{RED}Error: Source directory '{src_dir}' does not exist.{RESET}") return # Recursively find files files = [f for f in src_dir.rglob('*') if f.is_file()] if not files: print("No files found.") return print(f"Scanning {len(files)} files...") count_success = 0 count_skip = 0 for file_path in files: # Filter extensions if provided if args.ext and file_path.suffix.lower().lstrip('.') not in args.ext: continue # Get metadata date_meta = get_date_metadata(file_path) # Prepare template data template_data = { "year": date_meta.strftime("%Y"), "month": date_meta.strftime("%m"), "day": date_meta.strftime("%d"), "ext": file_path.suffix.lower(), "EXT": file_path.suffix.upper(), "original_name": file_path.stem } # Build destination path based on user pattern try: # e.g. pattern="{year}/{month}/{original_name}{ext}" rel_path_str = args.pattern.format(**template_data) full_dest_path = dest_base / rel_path_str except KeyError as e: print(f"{RED}Invalid pattern placeholder: {e}{RESET}") sys.exit(1) # Resolve conflicts final_path = get_unique_path(full_dest_path) # CLI Output action_verb = "Moving" if args.move else "Copying" prefix = f"{YELLOW}[DRY RUN]{RESET} " if args.dry_run else "" print(f"{prefix}{action_verb} {file_path.name} -> {final_path}") if not args.dry_run: # Create folders final_path.parent.mkdir(parents=True, exist_ok=True) try: if args.move: shutil.move(str(file_path), str(final_path)) else: shutil.copy2(str(file_path), str(final_path)) count_success += 1 except Exception as e: print(f"{RED}Failed to process {file_path.name}: {e}{RESET}") count_skip += 1 # Final Summary if not args.dry_run: print("-" * 30) print(f"{GREEN}Processed: {count_success}{RESET}") if count_skip > 0: print(f"{RED}Skipped/Errors: {count_skip}{RESET}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Organize and rename files based on metadata.") parser.add_argument("source", help="Source folder to scan") parser.add_argument("destination", help="Destination folder (base directory)") parser.add_argument( "--pattern", default="{year}/{month}/{original_name}{ext}", help="Naming pattern. Available: {year}, {month}, {day}, {original_name}, {ext}. Default: Creates Year/Month folders." ) parser.add_argument( "--move", action="store_true", help="Move files instead of copying (Delete from source)." ) parser.add_argument( "--dry-run", action="store_true", help="Simulate the process without making changes." ) parser.add_argument( "--ext", nargs="+", help="Only process specific extensions (e.g., jpg png mp4). Leave empty for all." ) args = parser.parse_args() if not HAS_PILLOW: print(f"{YELLOW}Warning: Pillow library not found. EXIF data extraction disabled. (pip install Pillow){RESET}") organize_files(args)How to use it
Run the script from your terminal.
1. Basic Organization (Copy mode)
Organizes files into
Year/Month/Filename.ext. This is the default safe mode (copies files).python organize.py ./my_messy_folder ./my_organized_folder2. Dry Run (Preview)
See what will happen without actually moving files. Highly recommended for the first run.
python organize.py ./messy ./clean --dry-run3. Move Files (Clean up source)
Use the
--moveflag to delete files from the source after organizing them.python organize.py ./messy ./clean --move4. Custom Renaming Pattern
You can completely restructure how files are named using the
--patternargument.- Example: Rename files to
YYYY-MM-DD_Filename.ext(Flat structure, no folders):python organize.py ./messy ./clean --pattern "{year}-{month}-{day}_{original_name}{ext}" - Example: Organize by Year only:
python organize.py ./messy ./clean --pattern "{year}/{original_name}{ext}"
5. Filter by File Type
Only organize specific files (e.g., only JPGs and PNGs).
python organize.py ./messy ./photos --ext jpg pngAvailable Placeholders
When defining your
--pattern, you can use these keys:{year}: 4-digit year (e.g., 2023){month}: 2-digit month (e.g., 10){day}: 2-digit day (e.g., 05){original_name}: The original filename (excluding extension){ext}: File extension in lowercase (e.g., .jpg){EXT}: File extension in uppercase (e.g., .JPG)
Code Logic Explanation
- Walk: Uses
pathlib.rglobto recursively find all files in the source folder. - Metadata:
- If the file is an image and
Pillowis installed, it reads theDateTimeOriginalEXIF tag. - If not, it falls back to the Operating System's creation date/modification date.
- If the file is an image and
- Formatting: It injects the metadata into your string format (the
--pattern). - Conflict Check: Before moving/copying, it checks if
file.jpgexists. If so, it generatesfile_1.jpg. - Execution: Uses
shutil.copy2(copies file + preserves metadata) orshutil.move.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.