Designing a Python tool
The user is asking for a Python tool that can batch-rename image files using EXIF data. I need to clarify their OS and library preferences, but I’m planning to use Pillow for this because it’s standard. The script will be a CLI tool that uses argparse to accept format patterns and manage various conditions like missing EXIF or collisions. I’ll also include an explanation for the code and how to use it in the command line.Drafting the image renaming tool
I need to design a tool to handle JPEG images, likely avoiding others like PNG since they typically lack EXIF data. I’m thinking of creating a simple, single-file CLI script without unnecessary extras. My initial script will import necessary libraries and define functions.
The key functions include one to get EXIF data and another to extract the datetime from it. I’ll set up a pattern for renaming files using placeholders like {datetime}. I want this to be efficient and clear for the user!Implementing the pattern processing
I’m working on implementing the code to handle the renaming patterns. I’ll treat placeholders like {datetime} and any specific formats that follow, such as {datetime:%Y%m%d_%H%M%S}. My plan is to use a custom pattern processor with regular expressions to match and format these patterns easily.
I’ll also create a function to build the new file names: it will extract variables from EXIF data and handle the original filename and extension. To manage datetime effectively, I’ll ensure to parse the string as needed for dynamic formatting.Refining the pattern formatting
I'm simplifying the pattern handling by using regex to manage the datetime placeholder. My format_pattern function will replace placeholders with their corresponding values from the context. If the context contains a datetime, I’ll format it correctly; if not, I’ll convert it to a string.
For situations where the datetime is missing, I plan to fall back to the file's modification time, ensuring we have a backup method for renaming. I’ll also implement options for starting the counter and handling naming collisions by adding suffixes when necessary. This should keep things straightforward!Preparing the batch renaming tool
I'm working on detailing the batch renaming tool that renames image files based on EXIF data. I’ll build functionalities, including a recursive option and specify acceptable file types. I'll set up the command-line interface to allow users to input a custom naming pattern and handle unexpected datetime values gracefully.
For each file being processed, I'll ensure to extract relevant EXIF data, apply necessary timezone shifts, and sanitize filenames to avoid any restricted characters. Finally, I’ll implement features to manage filename collisions and provide clear instructions for users on how to utilize the tool effectively. Below is a self‑contained command‑line tool in Python that batch‑renames image files using their EXIF data (typically date/time, camera make/model, etc.).
It supports:
- Recursive directory scanning
- Custom filename patterns
- Dry‑run mode
- Collision handling (won’t overwrite existing files)
- Fallback to file modification time if EXIF date is missing
1. Install dependency
pip install pillow
2. The script: rename_by_exif.py
#!/usr/bin/env python3
"""
Batch-rename image files based on EXIF data.
Example:
python rename_by_exif.py /path/to/images \
--pattern "{datetime:%Y%m%d_%H%M%S}_{model}" \
--recursive --dry-run
"""
import argparse
from datetime import datetime, timedelta
from pathlib import Path
import re
import sys
from PIL import Image, ExifTags
def load_exif(path: Path) -> dict:
"""
Return EXIF data as a dict with human-readable tag names.
If the file has no EXIF, return {}.
"""
exif_data = {}
try:
with Image.open(path) as img:
raw_exif = img._getexif() or {}
except Exception:
return {}
for tag_id, value in raw_exif.items():
tag_name = ExifTags.TAGS.get(tag_id, tag_id)
exif_data[tag_name] = value
return exif_data
def parse_exif_datetime(exif: dict) -> datetime | None:
"""
Try to extract and parse an EXIF date/time as a datetime object.
Checks DateTimeOriginal, DateTimeDigitized, DateTime.
Typical format: 'YYYY:MM:DD HH:MM:SS'
"""
for key in ("DateTimeOriginal", "DateTimeDigitized", "DateTime"):
value = exif.get(key)
if isinstance(value, bytes):
value = value.decode(errors="ignore")
if not isinstance(value, str):
continue
# Common EXIF format: 'YYYY:MM:DD HH:MM:SS'
try:
return datetime.strptime(value.strip(), "%Y:%m:%d %H:%M:%S")
except ValueError:
pass
# Try an ISO-like parse as a fallback
try:
# Handle strings like 'YYYY:MM:DD HH:MM:SS+HH:MM'
cleaned = value.strip()
# Replace first two ':' in date to turn it into ISO-ish 'YYYY-MM-DD ...'
parts = cleaned.split(" ")
if len(parts) >= 1 and ":" in parts[0]:
date_part = parts[0]
date_fixed = date_part.replace(":", "-", 2)
cleaned = " ".join([date_fixed] + parts[1:])
return datetime.fromisoformat(cleaned)
except Exception:
continue
return None
def sanitize_filename(text: str, replacement: str = "_") -> str:
"""
Remove characters that are invalid on common filesystems.
"""
invalid = r'<>:"/\|?*'
sanitized = "".join(replacement if c in invalid else c for c in str(text))
# Optionally collapse runs of replacement characters
sanitized = re.sub(re.escape(replacement) + r"+", replacement, sanitized)
return sanitized.strip()
def format_pattern(pattern: str, context: dict) -> str:
"""
Format a user pattern like:
"{datetime:%Y%m%d_%H%M%S}_{model}_{counter}"
using values in context (including datetime objects).
Available keys (by default):
datetime (datetime), make, model, orig_name, counter, ext
"""
def repl(match: re.Match) -> str:
key = match.group("key")
fmt = match.group("fmt")
value = context.get(key, "")
if isinstance(value, datetime):
if fmt:
return value.strftime(fmt)
# default datetime format if no explicit format given
return value.strftime("%Y%m%d_%H%M%S")
else:
if value is None:
return ""
if fmt:
# For non-datetime, use Python's format() with given spec
try:
return format(value, fmt)
except Exception:
return str(value)
return str(value)
pattern_re = re.compile(r"{(?P<key>\w+)(?::(?P<fmt>[^}]+))?}")
return pattern_re.sub(repl, pattern)
def ensure_unique_path(target: Path) -> Path:
"""
If target exists, append _1, _2, ... until a unique filename is found.
"""
if not target.exists():
return target
parent = target.parent
stem = target.stem
suffix = target.suffix
counter = 1
while True:
candidate = parent / f"{stem}_{counter}{suffix}"
if not candidate.exists():
return candidate
counter += 1
def iter_image_files(root: Path, exts: list[str], recursive: bool):
"""
Yield image files under root with the given extensions.
"""
exts = {e.lower() if e.startswith(".") else "." + e.lower() for e in exts}
if root.is_file():
if root.suffix.lower() in exts:
yield root
return
if recursive:
iterable = root.rglob("*")
else:
iterable = root.iterdir()
for p in iterable:
if p.is_file() and p.suffix.lower() in exts:
yield p
def rename_images(
path: Path,
pattern: str,
recursive: bool,
dry_run: bool,
exts: list[str],
tz_shift_hours: int,
start_counter: int,
):
files = sorted(iter_image_files(path, exts, recursive))
if not files:
print("No matching image files found.", file=sys.stderr)
return
counter = start_counter
renamed = 0
for img_path in files:
exif = load_exif(img_path)
dt = parse_exif_datetime(exif)
if dt is None:
# Fallback to file modification time
dt = datetime.fromtimestamp(img_path.stat().st_mtime)
if tz_shift_hours:
dt = dt + timedelta(hours=tz_shift_hours)
make = exif.get("Make", "")
model = exif.get("Model", "")
if isinstance(make, bytes):
make = make.decode(errors="ignore")
if isinstance(model, bytes):
model = model.decode(errors="ignore")
make = sanitize_filename(str(make).strip().replace(" ", "_"))
model = sanitize_filename(str(model).strip().replace(" ", "_"))
context = {
"datetime": dt,
"make": make,
"model": model,
"orig_name": img_path.stem,
"counter": counter,
"ext": img_path.suffix.lower().lstrip("."),
}
new_stem = format_pattern(pattern, context)
new_stem = sanitize_filename(new_stem) or img_path.stem
new_name = new_stem + img_path.suffix.lower()
target = img_path.with_name(new_name)
target = ensure_unique_path(target)
if target == img_path:
# Name unchanged
counter += 1
continue
print(f"{img_path.name} -> {target.name}")
if not dry_run:
try:
img_path.rename(target)
except Exception as e:
print(f" [ERROR] Could not rename {img_path} -> {target}: {e}", file=sys.stderr)
continue
renamed += 1
counter += 1
print(f"\nProcessed {len(files)} file(s); renamed {renamed} file(s).")
def main():
parser = argparse.ArgumentParser(
description="Batch-rename image files based on EXIF data."
)
parser.add_argument(
"path",
type=Path,
help="Image file or directory containing images.",
)
parser.add_argument(
"-p",
"--pattern",
default="{datetime:%Y%m%d_%H%M%S}_{orig_name}",
help=(
"Filename pattern (without extension). "
"Available fields: datetime, make, model, orig_name, counter, ext. "
'Example: "{datetime:%Y-%m-%d_%H-%M-%S}_{model}_{counter:04d}"'
),
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="Search directories recursively.",
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
help="Show what would be renamed, but do not actually rename files.",
)
parser.add_argument(
"-e",
"--extensions",
nargs="+",
default=[".jpg", ".jpeg", ".tif", ".tiff", ".png"],
help="Image file extensions to include (case-insensitive). Default: .jpg .jpeg .tif .tiff .png",
)
parser.add_argument(
"--timezone-shift",
type=int,
default=0,
help="Shift EXIF datetime by this many hours (can be negative).",
)
parser.add_argument(
"--start-counter",
type=int,
default=1,
help="Starting number for {counter} in the pattern.",
)
args = parser.parse_args()
if not args.path.exists():
print(f"Path not found: {args.path}", file=sys.stderr)
sys.exit(1)
rename_images(
path=args.path,
pattern=args.pattern,
recursive=args.recursive,
dry_run=args.dry_run,
exts=args.extensions,
tz_shift_hours=args.timezone_shift,
start_counter=args.start_counter,
)
if __name__ == "__main__":
main()
3. Usage examples
Basic: rename by capture date
python rename_by_exif.py /path/to/images
Default pattern is:
{datetime:%Y%m%d_%H%M%S}_{orig_name}
So e.g. IMG_1234.JPG with EXIF 2021:08:05 14:23:10 becomes:
20210805_142310_IMG_1234.jpg
Include camera model and sequential counter
python rename_by_exif.py /path/to/images \
--pattern "{datetime:%Y-%m-%d_%H-%M-%S}_{model}_{counter:04d}"
Example output:
2021-08-05_14-23-10_Canon_EOS_80D_0001.jpg
Recursive through subfolders, dry-run only
python rename_by_exif.py /path/to/images \
--recursive \
--pattern "{datetime:%Y%m%d_%H%M%S}_{make}_{model}" \
--dry-run
This prints the planned renames without changing anything.
Adjust for timezone offset
If your camera’s time is UTC but you want local time, e.g. UTC+2:
python rename_by_exif.py /path/to/images \
--timezone-shift 2
If you want this tailored further (e.g., integrate into a GUI, only rename files with EXIF, different collision logic), I can adjust the script accordingly.