The user wants a Python tool to batch-rename image files based on their EXIF data.
1. Understand the Goal:
The objective is to take a folder of images (likely JPEGs or RAW files) and rename them using metadata embedded in the files (the EXIF data). Common renaming patterns include using the date and time the photo was taken (e.g., 20230515_143022.jpg).
2. Identify Key Requirements:
- Input: A directory containing images.
- Processing:
- Iterate through files.
- Read EXIF data (specifically
DateTimeOriginal).
- Construct a new filename based on the EXIF date/time.
- Handle collisions (what if two photos were taken at the same second?).
- Preserve the file extension.
- Output: Renamed files in the directory.
- Safety: Needs to be careful not to overwrite files or crash on non-image files.
3. Choose the Right Tools (Libraries):
- Option A:
PIL / Pillow. Good for image manipulation, can read some EXIF, but sometimes finicky with specific tags or RAW files.
- Option B:
exif. A dedicated library, but maybe less common.
- Option C:
piexif. Pure python, easy to use, but only works well with JPEGs/TIFFs.
- Option D:
subprocess calling exiftool. The most robust solution for all file types, but requires the user to install external software.
- Selection:
Pillow is the standard for Python image tasks. It's usually sufficient for standard JPEGs/PNGs. I'll use Pillow because it's easiest to install via pip. I will also add a fallback or mention exiftool if they have weird RAW files, but for a general "Python tool," standard libraries are best.
4. Draft the Logic:
- Import:
os, PIL.Image.
- Function
get_exif_date(filepath):
- Open image.
- Get
_getexif().
- Look for tag 36867 (DateTimeOriginal).
- Parse the string (usually
YYYY:MM:DD HH:MM:SS).
- Format into a clean filename string (e.g.,
YYYY-MM-DD_HH-MM-SS).
- Error handling: If no EXIF, return None.
- Function
rename_images(directory):
- Loop through files in directory.
- Check if file is an image (by extension).
- Get date.
- If date exists:
- New name =
{date_string}{extension}.
- Collision check: If file exists, append
_1, _2, etc.
- Rename file (
os.rename).
- Print logs (success/skipped).
5. Refine the Code Structure:
- I should use
argparse to make it a command-line tool. This makes it a "tool" rather than just a script.
- Arguments:
path: Folder location.
--dry-run: To see what would happen without actually changing files. (Crucial for batch file operations).
--recursive: Maybe useful, but keep it simple for now.
6. Addressing Edge Cases:
- Non-image files: Ignore them.
- Missing EXIF: Skip or keep original name. (Skip is safer).
- Filename collisions: If two photos have the exact same second timestamp (burst mode), simple renaming will overwrite one.
- Solution: Check if the destination file exists. If so, append a counter.
7. Writing the Code (Mental Draft & Iteration):
-
Imports: os, sys, argparse, PIL.Image, PIL.UnidentifiedImageError.
-
Parsing EXIF:
The EXIF tag for DateTimeOriginal is 0x9003 (36867).
The format is "2023:01:01 12:00:00". I need to replace ":" with "-" or "" in the date part to make it file-system friendly.
Let's format it: YYYYMMDD_HHMMSS.
-
Collision Logic:
base_name = "20230101_120000"
ext = ".jpg"
new_name = base_name + ext
count = 1
while os.path.exists(new_name):
new_name = f"{base_name}_{count}{ext}"
count += 1
-
Dry Run: Just print [DRY RUN] Would rename: old.jpg -> new.jpg.
8. Final Polish:
Add comments, usage instructions, and dependency installation (pip install Pillow).
9. Constructing the Response:
- Prerequisites: Mention
Pillow.
- The Script: Provide the full, commented code.
- How to use: Show command line examples.
- Features: Highlight collision handling and dry-run mode.
(Self-Correction during drafting): Sometimes _getexif() returns None. I need to handle that. Also, sometimes the dictionary keys are integers, sometimes strings depending on the library version or specific implementation, but Pillow usually uses integer tags. I will define the tag constant explicitly. Tag 36867 is standard.
Let's write the actual code structure.
import os
import argparse
from PIL import Image
from PIL.ExifTags import TAGS
def get_exif_date(image_path):
try:
img = Image.open(image_path)
exif_data = img._getexif()
if exif_data:
# 36867 corresponds to DateTimeOriginal
for tag, value in exif_data.items():
if tag == 36867:
# Value format: "2023:05:20 14:30:00"
return value
except Exception:
pass
return None
Wait, I should probably handle the string replacement cleanly. value.replace(":", "").replace(" ", "_") turns "2023:05:20 14:30:00" into "20230520_143000". That looks good.
Let's add a generic get_date_from_exif that tries specific tags. Tag 36867 (DateTimeOriginal) is the best, 306 (DateTime) is the fallback.
10. Final Output Generation:
(Drafting the actual response provided in the good output).
Here is a robust, cross-platform Python script to batch-rename image files using their EXIF data.
Prerequisites
You will need the Pillow library (the modern fork of PIL) to read image data. Install it via pip:
pip install Pillow
The Python Script
Save the following code as rename_exif.py.
This script includes a "Dry Run" feature (enabled by default) so you can preview the changes before actually renaming any files. It handles file extension casing (e.g., .jpg vs .JPG) and prevents overwriting files if duplicates are found.
import os
import sys
import argparse
from PIL import Image, UnidentifiedImageError
from PIL.ExifTags import TAGS
def get_exif_creation_date(image_path):
"""
Opens an image and extracts the DateTimeOriginal tag.
Returns a string formatted as YYYY-MM-DD_HH-MM-SS or None if not found.
"""
try:
img = Image.open(image_path)
# _getexif returns a dictionary of EXIF data
exif_data = img._getexif()
if exif_data is None:
return None
# 36867 is the numeric ID for 'DateTimeOriginal'
# We iterate to find it just in case
for tag_id, value in exif_data.items():
tag_name = TAGS.get(tag_id, tag_id)
if tag_name == 'DateTimeOriginal':
# Standard EXIF format: "2023:05:20 14:30:00"
# We want to convert to: "2023-05-20_14-30-00"
date_str = value.replace(":", "-").replace(" ", "_")
return date_str
return None
except (AttributeError, KeyError, IndexError):
# Specific errors when EXIF might be corrupt or missing
return None
except UnidentifiedImageError:
# File is not an image
return None
except Exception as e:
print(f"Error reading {os.path.basename(image_path)}: {e}")
return None
def batch_rename(source_dir, dry_run=True):
# Validate directory
if not os.path.isdir(source_dir):
print(f"Error: Directory '{source_dir}' does not exist.")
return
print(f"Scanning directory: {source_dir}")
if dry_run:
print(">>> DRY RUN MODE: No files will be changed. <<<")
files_processed = 0
files_skipped = 0
# Get list of files
for filename in os.listdir(source_dir):
filepath = os.path.join(source_dir, filename)
# Skip directories
if os.path.isdir(filepath):
continue
# Attempt to read EXIF
exif_date = get_exif_creation_date(filepath)
if exif_date:
# Construct new filename
# Preserve original extension (lowercased for consistency)
ext = os.path.splitext(filename)[1].lower()
new_filename = f"{exif_date}{ext}"
new_filepath = os.path.join(source_dir, new_filename)
# Check if renaming is necessary
if filename == new_filename:
# print(f"Skipping '{filename}': Already named correctly.")
files_skipped += 1
continue
# Handle name collisions (if file already exists)
counter = 1
while os.path.exists(new_filepath):
new_filename = f"{exif_date}_{counter}{ext}"
new_filepath = os.path.join(source_dir, new_filename)
counter += 1
# Perform rename or Print preview
if dry_run:
print(f"[Dry Run] '{filename}' -> '{new_filename}'")
else:
try:
os.rename(filepath, new_filepath)
print(f"Renamed: '{filename}' -> '{new_filename}'")
except OSError as e:
print(f"Error renaming {filename}: {e}")
files_processed += 1
else:
# Could not find EXIF
# Optional: Uncomment below to see skipped files
# print(f"Skipped: '{filename}' (No EXIF data found)")
files_skipped += 1
print(f"\nDone. Processed: {files_processed}, Skipped: {files_skipped}")
if __name__ == "__main__":
# Setup Argument Parser
parser = argparse.ArgumentParser(description="Rename photos based on EXIF DateTimeOriginal.")
parser.add_argument("directory", help="Path to the folder containing images")
parser.add_argument("--execute", action="store_true", help="Actually rename files (default is dry run)")
args = parser.parse_args()
# If --execute is not passed, dry_run is True
batch_rename(args.directory, dry_run=not args.execute)
How to use it
1. Test it first (Dry Run)
By default, the script only prints what it would do. It won't change your files yet. Run this in your terminal:
python rename_exif.py "/path/to/your/photos"
2. Execute the Rename
If the output looks correct (e.g., IMG_001.jpg -> 2023-05-20_14-30-00.jpg), add the --execute flag to perform the actual renaming:
python rename_exif.py "/path/to/your/photos" --execute
How it works
- Safety First: The default mode is a "Dry Run." You must explicitly tell it to
--execute changes.
- Exif Extraction: It looks for the
DateTimeOriginal tag (ID 36867), which is the standard tag cameras use to store the exact moment the shutter snapped.
- Sanitization: It converts the standard EXIF date format (
2023:05:20 14:30:00) into a file-system friendly format (2023-05-20_14-30-00).
- Collision Handling: If you have two photos taken in the same second (burst mode), the script automatically appends
_1, _2, etc., to the filename so you don't lose any photos.
- Skipping: It silently skips files that don't have EXIF data (like PNGs generated by image editors or screenshots) or files that are already named correctly.