#!/bin/env python3 # vim: noexpandtab ts=4 ft=python : """ Rename all jpg images in the current folder. If there is a NEF image with the same same, rename it as well. """ import os import re import datetime import operator import PIL.Image import PIL.ExifTags def get_date(filename): """ Get date and time from image exif tag and return string with format %Y%m%d_%H%M%S """ try: img = PIL.Image.open(filename) e = img._getexif() if 306 in e: index = 306 elif 36867 in e: index = 36867 elif 36838 in e: index = 36868 d = datetime.datetime.strptime(e[index], "%Y:%m:%d %H:%M:%S") img.close() return d.strftime("%Y%m%d_%H%M%S") except Exception as e: print(e) exit(2) return None def print_new_filename(number, date, name, original_filename): ext = original_filename.split('.')[-1] return "%s_%s_%03d.%s" % (date, name, number, ext.lower()) def rename_file_and_nef(number, date, name, original_filename): ext = original_filename.split('.')[-1].lower() plain = ".".join(original_filename.split('.')[:-1]) name = "%s_%s_%03d" % (date, name, number) print("Handling file %s..." % (original_filename, )) print(" Renaming from '%s' to '%s'" % (original_filename, name + "." + ext)) os.rename(os.path.join(os.getcwd(), original_filename), os.path.join(os.getcwd(), name + "." + ext)) if os.path.isfile(os.path.join(os.getcwd(), plain + ".NEF")): print(" Renaming from '%s' to '%s'" % (plain + ".NEF", name + ".nef")) os.rename(os.path.join(os.getcwd(), plain + ".NEF"), os.path.join(os.getcwd(), name + ".nef")) elif os.path.isfile(os.path.join(os.getcwd(), plain + ".nef")): print(" Renaming from '%s' to '%s'" % (plain + ".nef", name + ".nef")) os.rename(os.path.join(os.getcwd(), plain + ".nef"), os.path.join(os.getcwd(), name + ".nef")) if PIL.ExifTags.TAGS[306] != "DateTime": print("Warning: EXIF index for DateTime changed!") exit(2) images = [[get_date(os.path.join(os.getcwd(), f)), f] for f in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), f)) and re.search(r'\.jpe?g$', f, flags=re.IGNORECASE)] images = sorted(images, key=operator.itemgetter(0, 1)) i = 1 for img in images: rename_file_and_nef(i, img[0], "mfg-who-am-i", img[1]) i += 1