The user wants a Python CLI tool to rename and organize files based on metadata. Since they haven't provided specific details, I should propose a design, features, and a code example. I’m thinking about incorporating various metadata types like EXIF for images, audio metadata (ID3), and document properties. The CLI will work on directories, apply patterns, and allow for dry runs and logging. I might also need to ask a few clarifying questions. I plan to use argparse, pathspec, and maybe libraries like exifread or mutagen.Designing Metadata Renamer
To rename files using metadata like EXIF or ID3, I'll need some libraries but will keep them optional for graceful degradation. I'm thinking of naming the tool "metarenamer" or "meta-organizer."
The design would use Python 3.9+, and the CLI syntax could look something like this:
The features might include accepting a directory, recursively processing files, and allowing mode selection based on file types. I'll implement core features using generic metadata keys and support specific fields for images and audio.Simplifying Photo Support
For now, I’ll focus on supporting photos using libraries like exifread or Pillow for metadata extraction, and I’ll use filesystem times as a fallback. The user might just want a sample tool, so I can mention optional extras too.
I'll create a script called meta_organizer.py, and I need to implement a robust method for slugifying strings into safe filenames. I’ll also address filename collisions by adding suffix numbers or skipping.
The argparse options will include a positional path, an optional destination, a filename pattern, and an optional directory pattern that can handle date formatting. I'll parse the metadata keys with mini-format syntax to facilitate this!Extracting Metadata
I’m thinking about how to interpret placeholders in my filename template. For any {field}, it should translate to str(value). If the value is a datetime and the pattern includes formatting like :%Y-%m-%d, I'll pass it to strftime. Otherwise, I’ll treat it as f"{value:{fmt}}".
I need to create a function called extract_metadata(path) that returns a dictionary. This function will gather generic file data (stem, name, ext, size, and various timestamps).
For image files, I'll parse EXIF data using Pillow’s Image.open, only supporting JPEG and TIFF formats. I’ll build an exif_ dictionary and look specifically for the EXIF DateTimeOriginal or DateTime tag to extract the date taken.Implementing Metadata Extraction
I'm planning to unify metadata extraction for both datetime and camera details while ensuring graceful handling of unavailability. For audio, I can optionally use the mutagen library, but I’m thinking I’ll include it without making it mandatory. If it’s not available, I can simply skip audio tags.
I'll need CLI options like --dry-run, --recursive, and --include/--exclude patterns. Given the user simply requested a Python CLI tool to rename and organize files based on metadata, I can also provide a setup.py example for packaging.
My intention is to deliver a single script along with usage documentation. In the code, I'll document the parameters and outline essential functions. I’ll also include logic to handle edge cases like avoiding moving a file onto itself and managing name collisions by creating new filenames with suffixes.
For metadata placeholders, I'll document keys such as:
EXIF: date_taken, camera_make, camera_model, and raw EXIF tags.
I’ll implement a function for rendering the template using a custom string formatter to handle date and non-date fields properly. Additionally, I’ll ensure all paths are sanitized to avoid illegal characters after formatting. Finally, I’ll keep the code focused on correctness and simplicity.Preparing CLI Steps for File Organization
I'm outlining steps for the CLI: first, I'll need to parse arguments. For each file path, I will extract metadata and build a new path using build_target_path. This function will create directory structures based on a specified template.
I need to carefully handle slugifying filenames to correct for any illegal characters but ensure the file extension remains intact. I'll implement a slugify function for this.
Next, I’ll define the main plan_operations function to prepare operations and handle potential conflicts when renaming files. I'll include comprehensive CLI options that allow for organizing files flexibly.
Finally, I'll ensure to illustrate examples for users, showing how they could rename and organize files based on metadata, balancing functionality with simplicity. My goal is to provide a complete, functioning script along with minimal necessary documentation for effective usage.Finalizing CLI Tool and Metadata Extraction
I’m compiling usage examples for the CLI tool, showcasing how to organize photos into a directory structure based on the date taken. The first example demonstrates a dry-run to visualize changes without applying them, while the second one shows how to execute the actual renaming.
Next, I'm ensuring the script imports necessary libraries, like Pillow for EXIF data, handling exceptions for optional imports. Additionally, I’m defining the slugify function to sanitize filenames and metadata extraction functions to gather essential file information. This step will help keep the file organization process efficient and user-friendly.Finalizing Script Details
I’m ensuring the docstring patterns in the argparse description correctly escape the percent signs, noting that they need to be formatted as '%%Y' for clarity. Adjusting the help text for --dir-pattern will help users better understand the format.
Next, I’ll double-check my imports — I see os is unused, but maybe I’ll leave it in case I need it later. Finally, in the apply_renames function, I'm confirming that I’m using rel_src and rel_dst, which looks fine. Everything seems to be coming together nicely!Clarifying Import and Documentation Issues
I’ve spotted a potential issue with importing ExifTags. We need to ensure that if Image is imported but ExifTags fails, we set both to None safely. Spacing in the import section looks fine.
I noticed another problem: in the --dir-pattern help text, we're incorrectly leaving the % unescaped in the example for %%m. It’s unnecessary since we treat the pattern as a raw string. I also need to clarify that when using argparse.ArgumentParser, the percent signs must be doubled for any formatting.
Now, it's important to provide a clear final message regarding the code, including a minimal usage explanation. It’s also good to note that users need to install Pillow for EXIF features with pip install pillow, although the script will still work with mtime as the date_taken if Pillow isn’t there. I should also suggest they can easily put the script on their PATH or install it as a package. Crafting this final answer will include code snippets, bullet-point feature explanations, and quick usage examples, keeping it under 1,000 words. Below is a self‑contained Python CLI tool that renames and organizes files based on filesystem metadata and (optionally) EXIF metadata for photos.
Save it as meta_organizer.py, make it executable, and run from the command line.
python
Usage summary:
Install Pillow for EXIF support:
bash
pip install pillow
Run on a directory, grouping photos by year/month and using EXIF date:
bash
python meta_organizer.py ~/Pictures \
--recursive \
--dir-pattern "{date_taken:%Y}/{date_taken:%m}" \
--pattern "{date_taken:%Y%m%d_%H%M%S}_{camera_model}{ext}" \
--dry-run # remove this when you're happy
If you want, I can tailor the patterns and defaults for a specific use case (photos, music, documents, etc.).
#!/usr/bin/env python3
"""
meta_organizer.py - Rename and organize files based on metadata.
Examples:
# Dry-run: photos into YYYY/MM, filenames from EXIF date taken
python meta_organizer.py ~/Pictures \
--recursive \
--dir-pattern "{date_taken:%Y}/{date_taken:%m}" \
--pattern "{date_taken:%Y%m%d_%H%M%S}_{camera_model}{ext}" \
--dry-run
# In-place rename by modified date
python meta_organizer.py ~/Downloads \
--recursive \
--pattern "{mtime:%Y-%m-%d_%H-%M-%S}_{stem}{ext}"
Requires:
- Python 3.8+
- For EXIF photo metadata: Pillow (pip install pillow)
"""
import argparse
import re
import sys
import string
import unicodedata
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Dict, Iterable, List, Optional
# Optional Pillow for EXIF
try:
from PIL import Image, ExifTags
except Exception: # ImportError or others
Image = None
ExifTags = None
@dataclass
class RenameOperation:
src: Path
dst: Path
class MetaFormatter(string.Formatter):
"""Formatter that knows how to format datetime metadata."""
def get_value(self, key, args, kwargs):
# Missing fields are replaced by empty string instead of KeyError
if isinstance(key, str):
return kwargs.get(key, "")
return super().get_value(key, args, kwargs)
def format_field(self, value, format_spec):
from datetime import date, datetime
if isinstance(value, (datetime, date)):
if format_spec:
return value.strftime(format_spec)
return value.isoformat()
return super().format_field(value, format_spec)
formatter = MetaFormatter()
def slugify(text: str) -> str:
"""Make a filesystem-safe slug from arbitrary text."""
if not text:
return ""
# Normalize unicode to ASCII
text = unicodedata.normalize("NFKD", text)
text = text.encode("ascii", "ignore").decode("ascii")
# Replace path separators and illegal chars
text = re.sub(r"[\\/:*?\"<>|]+", "_", text)
# Replace other non-word characters with underscore
text = re.sub(r"[^\w\.\-]+", "_", text)
# Collapse multiple underscores / dots
text = re.sub(r"_+", "_", text)
text = re.sub(r"\.+", ".", text)
return text.strip(" ._")
def slugify_filename(name: str) -> str:
p = Path(name)
stem = slugify(p.stem)
ext = p.suffix # keep extension as-is
return (stem or "unnamed") + ext
def extract_exif_metadata(path: Path) -> Dict[str, object]:
meta: Dict[str, object] = {}
if not Image:
return meta
if path.suffix.lower() not in (".jpg", ".jpeg", ".tif", ".tiff"):
return meta
try:
with Image.open(path) as img:
exif_raw = img._getexif() or {}
except Exception:
return meta
if not exif_raw:
return meta
# Build readable tags
tag_map = {ExifTags.TAGS.get(k, str(k)): v for k, v in exif_raw.items()}
meta["exif"] = tag_map
# Date taken
dt_str = (
tag_map.get("DateTimeOriginal")
or tag_map.get("DateTimeDigitized")
or tag_map.get("DateTime")
)
if isinstance(dt_str, bytes):
dt_str = dt_str.decode(errors="ignore")
if isinstance(dt_str, str):
for fmt in ("%Y:%m:%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"):
try:
meta["date_taken"] = datetime.strptime(dt_str, fmt)
break
except ValueError:
continue
# Camera info
make = tag_map.get("Make")
model = tag_map.get("Model")
if make:
meta["camera_make"] = str(make).strip()
if model:
meta["camera_model"] = str(model).strip()
return meta
def extract_metadata(path: Path) -> Dict[str, object]:
"""Return a metadata dict for this file.
Generic keys:
- name, stem, ext, ext_no_dot, parent
- size (bytes)
- mtime, ctime, atime (datetime)
- path (string)
Image/EXIF:
- date_taken (datetime; fallback to mtime)
- camera_make, camera_model (if present)
"""
st = path.stat()
meta: Dict[str, object] = {
"name": path.name,
"stem": path.stem,
"ext": path.suffix,
"ext_no_dot": path.suffix.lstrip("."),
"parent": path.parent.name,
"size": st.st_size,
"mtime": datetime.fromtimestamp(st.st_mtime),
"ctime": datetime.fromtimestamp(st.st_ctime),
"atime": datetime.fromtimestamp(st.st_atime),
"path": str(path),
}
# Add EXIF metadata for images
meta.update(extract_exif_metadata(path))
# Ensure date_taken is always set
meta.setdefault("date_taken", meta["mtime"])
return meta
def render_template(template: str, meta: Dict[str, object]) -> str:
if not template:
return ""
try:
return formatter.format(template, **meta)
except Exception as e:
raise ValueError(f"Template error '{template}': {e}") from e
def build_target_path(
src: Path,
meta: Dict[str, object],
dest_root: Path,
dir_pattern: Optional[str],
file_pattern: str,
) -> Path:
# Directory pattern -> relative directory under dest_root
rel_dir = Path()
if dir_pattern:
dir_str = render_template(dir_pattern, meta)
if dir_str:
# Allow user to use "/" in pattern for nested dirs
rough = Path(dir_str)
parts = [slugify(p) for p in rough.parts if p]
if parts:
rel_dir = Path(*parts)
# File pattern -> filename
file_str = render_template(file_pattern, meta)
if not file_str:
file_str = src.name
# If user forgot to include extension, add original one
if not Path(file_str).suffix and "{ext" not in file_pattern and "{ext_no_dot" not in file_pattern:
file_str += src.suffix
safe_name = slugify_filename(file_str)
return dest_root / rel_dir / safe_name
def iter_files(root: Path, recursive: bool) -> Iterable[Path]:
if root.is_file():
yield root
return
if recursive:
for p in root.rglob("*"):
if p.is_file():
yield p
else:
for p in root.iterdir():
if p.is_file():
yield p
def filter_by_ext(
files: Iterable[Path],
include_ext: Optional[List[str]],
exclude_ext: Optional[List[str]],
) -> Iterable[Path]:
inc = {e.lower().lstrip(".") for e in include_ext} if include_ext else None
exc = {e.lower().lstrip(".") for e in exclude_ext} if exclude_ext else set()
for p in files:
ext = p.suffix.lower().lstrip(".")
if inc is not None and ext not in inc:
continue
if ext in exc:
continue
yield p
def ensure_unique_path(target: Path) -> Path:
"""If target exists, append _1, _2, ... before extension."""
if not target.exists():
return target
parent = target.parent
stem = target.stem
ext = target.suffix
i = 1
while True:
cand = parent / f"{stem}_{i}{ext}"
if not cand.exists():
return cand
i += 1
def plan_renames(
sources: Iterable[Path],
dest_root: Path,
dir_pattern: Optional[str],
file_pattern: str,
overwrite: bool,
) -> List[RenameOperation]:
ops: List[RenameOperation] = []
for src in sources:
meta = extract_metadata(src)
dst = build_target_path(src, meta, dest_root, dir_pattern, file_pattern)
if dst == src:
continue
if dst.exists() and dst != src:
if overwrite:
# OK, will overwrite
pass
else:
dst = ensure_unique_path(dst)
ops.append(RenameOperation(src=src, dst=dst))
return ops
def apply_renames(ops: List[RenameOperation], dry_run: bool, verbose: bool) -> None:
for op in ops:
if dry_run:
print(f"[DRY-RUN] {op.src} -> {op.dst}")
continue
if verbose:
print(f"{op.src} -> {op.dst}")
op.dst.parent.mkdir(parents=True, exist_ok=True)
op.src.rename(op.dst)
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Rename and organize files based on filesystem and EXIF metadata."
)
p.add_argument(
"path",
type=str,
help="Source file or directory to process.",
)
p.add_argument(
"--dest",
type=str,
default=None,
help="Destination root directory (default: in-place).",
)
p.add_argument(
"--pattern",
type=str,
default="{stem}{ext}",
help=(
"Filename template. Available fields include: "
"{stem}, {ext}, {ext_no_dot}, {parent}, {size}, "
"{mtime}, {ctime}, {date_taken}, {camera_model}, etc. "
"Use date formatting like {date_taken:%%Y-%%m-%%d_%%H%%M%%S}."
),
)
p.add_argument(
"--dir-pattern",
type=str,
default=None,
help=(
"Directory template, relative to destination root. "
"Example: '{date_taken:%%Y}/%%m' to group by year/month."
),
)
p.add_argument(
"-r",
"--recursive",
action="store_true",
help="Recurse into subdirectories if PATH is a directory.",
)
p.add_argument(
"--include-ext",
nargs="*",
help="Only process files with these extensions (e.g. jpg png pdf).",
)
p.add_argument(
"--exclude-ext",
nargs="*",
help="Skip files with these extensions.",
)
p.add_argument(
"--overwrite",
action="store_true",
help="Overwrite existing files at the destination instead of adding suffix.",
)
p.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without actually renaming/moving files.",
)
p.add_argument(
"-v",
"--verbose",
action="store_true",
help="Print each rename as it happens.",
)
return p.parse_args(argv)
def main(argv: Optional[List[str]] = None) -> int:
args = parse_args(argv)
src_path = Path(args.path).expanduser().resolve()
if not src_path.exists():
print(f"Source path does not exist: {src_path}", file=sys.stderr)
return 1
if args.dest:
dest_root = Path(args.dest).expanduser().resolve()
else:
# In-place: if path is file, root is its parent; if dir, root is it.
dest_root = src_path.parent if src_path.is_file() else src_path
files = list(iter_files(src_path, recursive=args.recursive))
files = list(filter_by_ext(files, args.include_ext, args.exclude_ext))
if not files:
print("No files to process.")
return 0
ops = plan_renames(
files,
dest_root=dest_root,
dir_pattern=args.dir_pattern,
file_pattern=args.pattern,
overwrite=args.overwrite,
)
if not ops:
print("Nothing to rename; all files already match the target pattern.")
return 0
apply_renames(ops, dry_run=args.dry_run, verbose=args.verbose or args.dry_run)
if args.dry_run:
print(f"{len(ops)} operation(s) planned (dry-run only).")
else:
print(f"{len(ops)} file(s) renamed/moved.")
return 0
if __name__ == "__main__":
raise SystemExit(main())