Sort JPEG-files by date within the EXIF-data into folders

11.11.2020, 14:27 - Autor: Mark B.
This tool check all JPEG-files within a folder and check the date in the EXIF-data to sort the photos to a folder-structure like that:

D:\DE\case12345\2019\2019-12-24
D:\DE\case12345\2019\2019-12-31
D:\DE\case12345\2020\2020-01-01

... a main-folder for each year with subfolders for each date.

Source:

import os, time, hashlib, PIL
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from PIL import Image

root = tk.Tk()
root.withdraw()

# Select base folder
base_folder = filedialog.askdirectory(parent=root, initialdir="/", title='Please select the base-directory')

if base_folder is not None:
        files = os.listdir(base_folder)

        year_db = set()
        date_db = set()
        file_db = {}

        print("Creating database ", end="")
        for f in files:
                fpath = os.path.join(base_folder, f)
                try:
                        exif = Image.open(fpath)._getexif()[36867]

                        # Check year
                        tmp = exif.split(" ")[0].split(":")
                        
                        # Split by / if : don't work
                        if len(tmp) < 3:
                            tmp = exif.split(" ")[0].split("/")
                        # Split by - if : and / don't work
                        if len(tmp) < 3:
                            tmp = exif.split(" ")[0].split("-")
                        # Skip this file if none of above worked
                        if len(tmp) < 3:
                            continue
                        
                        # Add to DB
                        year_db.add(tmp[0])

                        # Check folder
                        date_folder = tmp[0] + "-" + tmp[1] + "-" + tmp[2]
                        date_db.add(date_folder)

                        # Save file - folder relation
                        file_db[fpath] = date_folder

                except (OSError, IndexError) as e:
                        pass

        print("... DONE!")

        # Create folders
        for year in year_db:
            new_folder = os.path.join(base_folder, year)
            if not os.path.isdir(new_folder):
                os.mkdir(new_folder)

        for dir_name in date_db:
            year = dir_name[0:4]
            new_folder = os.path.join(os.path.join(base_folder, year), dir_name)
            if not os.path.isdir(new_folder):
                os.mkdir(new_folder)

        # Move files
        for fpath, dir_name in file_db.items():
            year = dir_name[0:4]
            new_folder = os.path.join(os.path.join(base_folder, year), dir_name)
            
            file_name = os.path.basename(fpath)
            new_path = os.path.join(new_folder, file_name)
            print(f"{fpath} -> {new_path}")

            os.rename(fpath, new_path)
        

Download


System requrements:

Windows, OSX or Linux with