The Palos Publishing Company

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

Rename files based on EXIF data

Renaming files based on EXIF data—especially photos—is a common task for organizing images by the date and time they were taken. Here’s a Python script that uses the Pillow and os libraries to rename image files in a folder based on their EXIF metadata (e.g., YYYY-MM-DD_HH-MM-SS.jpg).


🐍 Python Script: Rename Files Using EXIF Metadata

python
import os from PIL import Image from PIL.ExifTags import TAGS from datetime import datetime def get_exif_datetime(image_path): try: image = Image.open(image_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 value except Exception as e: print(f"Error reading EXIF from {image_path}: {e}") return None def format_datetime(exif_datetime): try: dt = datetime.strptime(exif_datetime, '%Y:%m:%d %H:%M:%S') return dt.strftime('%Y-%m-%d_%H-%M-%S') except Exception as e: print(f"Error formatting EXIF datetime: {e}") return None def rename_images_in_directory(directory): for filename in os.listdir(directory): if filename.lower().endswith(('.jpg', '.jpeg')): full_path = os.path.join(directory, filename) exif_datetime = get_exif_datetime(full_path) if exif_datetime: formatted_name = format_datetime(exif_datetime) if formatted_name: new_filename = f"{formatted_name}.jpg" new_full_path = os.path.join(directory, new_filename) counter = 1 while os.path.exists(new_full_path): new_filename = f"{formatted_name}_{counter}.jpg" new_full_path = os.path.join(directory, new_filename) counter += 1 os.rename(full_path, new_full_path) print(f"Renamed: {filename}{new_filename}") else: print(f"Skipping {filename}: Failed to format EXIF date") else: print(f"Skipping {filename}: No EXIF date found") # Example usage: # rename_images_in_directory("/path/to/your/images")

📌 Notes:

  • Only processes .jpg and .jpeg files.

  • Skips files without DateTimeOriginal EXIF tag.

  • Prevents overwriting by appending a counter if a filename already exists.

Let me know if you want this adapted for other EXIF tags (like camera model) or file types (like .png, though they rarely have EXIF).

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