Defining the Script's Purpose
I'm now zeroing in on the core function. The idea is crystal clear: design a Python script to perform batch renaming. The key is in pulling EXIF data out of the image files (date taken, camera model, etc.) so I can get exactly what information to incorporate into the new filenames. This step is pivotal for accurate renaming.
Developing the Workflow
My focus has shifted towards the logical flow of the script. I've broken down the process: get the image files, identify their EXIF data, format the date/time, and rename them. Handling duplicates will be key to avoiding issues. I am now considering incorporating error handling. I'll need to account for files without EXIF data or images of other formats than I had originally anticipated. I am ready to start on the setup portion of the script.
Integrating EXIF Extraction
I'm now fully immersed in the EXIF data extraction phase. I'm focusing on handling potential errors like missing EXIF data or corrupted files to ensure the script's robustness. The current implementation uses a get_date_taken function to retrieve the date and time. It employs PIL and ExifTags to map the integer keys to readable labels. I'm considering using DateTimeOriginal, DateTimeDigitized and DateTime fields to get the most accurate date. Now, I will start to implement the renaming workflow based on the extracted metadata.
Finalizing Duplicate Handling
I'm now implementing the core renaming logic. I've designed the script to incorporate sequential numbering if duplicate names occur, like "2023-10-01_12-00-00_1.jpg". I'm also ensuring the original file extensions are preserved during renaming. I've integrated a "Dry Run" mode for safer testing, letting users preview changes before execution. Finally, I'm using argparse for command-line arguments.
Constructing the Core Loop
I'm now building the central loop of the script. This loop handles argument parsing and iterates through each file. I've designed logic to extract date information, construct the new filename, and manage potential filename collisions using a counter. I'm focusing on robust error handling to address files lacking EXIF data. Before executing the rename, I'll print a dry-run message, for previewing proposed changes. I'll stick with skipping and warning if EXIF data is missing, to avoid confusing behavior.
Addressing Error Cases
I'm now refining the script's error handling. I'm focusing on ensuring it gracefully manages situations where files are inaccessible or have unexpected formats. I've integrated checks to skip such files and provide informative error messages to the user. I've also implemented logging for debugging purposes, capturing details about skipped files or issues encountered during the renaming process. This helps in pinpointing any problems during real-world usage.
Here is a robust, command-line Python tool using the Pillow library to read EXIF metadata and pathlib for file handling.
This script includes a Dry Run feature (on by default) to prevent accidental renaming without verification.
Prerequisites
You will need to install the Pillow library to handle image metadata:
pip install Pillow
The Python Script (rename_by_exif.py)
import os
import sys
import argparse
from pathlib import Path
from datetime import datetime
from PIL import Image, UnidentifiedImageError
# Formats to look for in EXIF data
# Standard EXIF date format is 'YYYY:MM:DD HH:MM:SS'
EXIF_DATE_FORMAT = '%Y:%m:%d %H:%M:%S'
# Output filename format
OUTPUT_FORMAT = '%Y-%m-%d_%H-%M-%S'
def get_date_taken(image_path):
"""
Extracts the 'DateTimeOriginal' from image EXIF data.
Returns a datetime object or None if not found.
"""
try:
with Image.open(image_path) as img:
exif_data = img._getexif()
if not exif_data:
return None
# Iterate through tags to find date
# 36867 is the tag ID for DateTimeOriginal
# 306 is the tag ID for DateTime (fallback)
date_str = exif_data.get(36867) or exif_data.get(306)
if date_str:
try:
return datetime.strptime(date_str, EXIF_DATE_FORMAT)
except ValueError:
return None
except (UnidentifiedImageError, OSError):
# Not an image or corrupted
return None
except Exception as e:
print(f"Error reading {image_path.name}: {e}")
return None
return None
def get_unique_path(directory, original_stem, extension, dt_obj):
"""
Generates a unique filename. If collision exists, appends a counter.
Ex: 2023-01-01_12-00-00.jpg -> 2023-01-01_12-00-00_1.jpg
"""
base_name = dt_obj.strftime(OUTPUT_FORMAT)
new_filename = f"{base_name}{extension}"
new_path = directory / new_filename
counter = 1
while new_path.exists():
# Check if we are renaming the file to itself
if new_path.name == f"{original_stem}{extension}":
return None
new_filename = f"{base_name}_{counter}{extension}"
new_path = directory / new_filename
counter += 1
return new_path
def process_images(directory, dry_run=True):
target_dir = Path(directory)
if not target_dir.exists():
print(f"Error: Directory '{directory}' not found.")
return
files = [f for f in target_dir.iterdir() if f.is_file()]
valid_exts = {'.jpg', '.jpeg', '.tiff', '.webp'} # PNG usually doesn't contain EXIF standardly
renamed_count = 0
skipped_count = 0
print(f"{'--- DRY RUN MODE ---' if dry_run else '--- PROCESSING ---'}\n")
for file_path in files:
if file_path.suffix.lower() not in valid_exts:
continue
date_taken = get_date_taken(file_path)
if date_taken:
new_path = get_unique_path(target_dir, file_path.stem, file_path.suffix, date_taken)
if new_path is None:
# File is already named correctly
skipped_count += 1
continue
if dry_run:
print(f"[Would Rename] {file_path.name} -> {new_path.name}")
else:
try:
file_path.rename(new_path)
print(f"[Renamed] {file_path.name} -> {new_path.name}")
renamed_count += 1
except OSError as e:
print(f"[Error] Could not rename {file_path.name}: {e}")
else:
print(f"[Skipped] {file_path.name} (No EXIF Date found)")
skipped_count += 1
print("\nSummary:")
print(f"Processed: {renamed_count} files")
print(f"Skipped: {skipped_count} files (No Metadata, non-images, or already named correctly)")
if dry_run:
print("\n(No changes were made. Run with --execute to apply changes)")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Batch rename images based on EXIF 'Date Taken'")
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()
process_images(args.directory, dry_run=not args.execute)
How to use it
- Save the code above into a file, for example:
renamer.py.
- Run a "Dry Run" (Safe Mode):
This checks the folder and prints what would happen without actually changing any filenames.
python renamer.py ./my_photos
- Execute the Rename:
Once you are happy with the proposed changes, add the
--execute flag to perform the renaming.
python renamer.py ./my_photos --execute
Features Explained
- Collision Handling:
If you took 3 photos in the exact same second, the script automatically names them:
2023-10-25_14-30-01.jpg
2023-10-25_14-30-01_1.jpg
2023-10-25_14-30-01_2.jpg
- Safety Filters:
- It ignores non-image files.
- If an image has no EXIF data (e.g., a screenshot or a stripped image), it skips it rather than deleting it or naming it
None.jpg.
- It uses
pathlib, which handles different operating system path styles (Windows vs Mac/Linux) automatically.
- Context Manager:
It uses
with Image.open() as img: to ensure the image file is closed immediately after reading the data. This prevents "File in use" errors on Windows when trying to rename the file immediately after reading it.