The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a file renaming utility for photo albums

Here’s a file renaming utility for photo albums built in Python. It renames photos in a selected folder based on the date taken (from EXIF metadata) or last modified time, and allows for a custom naming pattern.

python
import os import re import time from datetime import datetime from pathlib import Path from PIL import Image from PIL.ExifTags import TAGS def get_exif_date_taken(img_path): try: image = Image.open(img_path) exif_data = image._getexif() if not exif_data: return None for tag_id, value in exif_data.items(): tag = TAGS.get(tag_id, tag_id) if tag == 'DateTimeOriginal': return datetime.strptime(value, '%Y:%m:%d %H:%M:%S') except Exception: return None return None def rename_photos_in_directory(directory, name_pattern="Photo", use_exif=True): directory = Path(directory) if not directory.exists() or not directory.is_dir(): print("Invalid directory.") return image_extensions = ['.jpg', '.jpeg', '.png', '.heic', '.webp'] photos = [f for f in directory.iterdir() if f.suffix.lower() in image_extensions] counter = 1 for photo in sorted(photos): date_taken = get_exif_date_taken(photo) if use_exif else None if not date_taken: date_taken = datetime.fromtimestamp(photo.stat().st_mtime) timestamp_str = date_taken.strftime('%Y%m%d_%H%M%S') new_filename = f"{name_pattern}_{timestamp_str}_{counter:03d}{photo.suffix.lower()}" new_filepath = directory / new_filename while new_filepath.exists(): counter += 1 new_filename = f"{name_pattern}_{timestamp_str}_{counter:03d}{photo.suffix.lower()}" new_filepath = directory / new_filename os.rename(photo, new_filepath) print(f"Renamed: {photo.name} -> {new_filename}") counter += 1 if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Rename photo files in a directory by date taken.") parser.add_argument("directory", help="Path to the folder containing photos") parser.add_argument("--pattern", default="Photo", help="Base name pattern for renamed files") parser.add_argument("--no-exif", action="store_true", help="Do not use EXIF data, use file modified time instead") args = parser.parse_args() rename_photos_in_directory(args.directory, name_pattern=args.pattern, use_exif=not args.no_exif)

Features:

  • Automatically uses EXIF date taken if available (or file modification time otherwise).

  • Customizable naming pattern (--pattern).

  • Supports popular image formats.

  • Handles file name collisions by adding a counter.

Would you like a version with a GUI or drag-and-drop support?

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About