Created
December 28, 2024 18:43
-
-
Save RemDelaporteMathurin/80668836c6f002aa31ea9eecbb678977 to your computer and use it in GitHub Desktop.
Script for sorting photos by date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
from datetime import datetime | |
from PIL import Image | |
from PIL.ExifTags import TAGS | |
import sys | |
def get_exif_data(image_path: str): | |
image = Image.open(image_path) | |
exif_data = image._getexif() | |
if exif_data is not None: | |
for tag, value in exif_data.items(): | |
decoded = TAGS.get(tag, tag) | |
if decoded == "DateTimeOriginal": | |
return value | |
print(f"No EXIF data found {image_path}") | |
return None | |
def get_creation_date(file_path: str): | |
try: | |
exif_date = get_exif_data(file_path) | |
if exif_date: | |
return datetime.strptime(exif_date, "%Y:%m:%d %H:%M:%S") | |
except Exception as e: | |
print(f"Error getting EXIF data: {e}") | |
# return datetime.fromtimestamp(os.path.getmtime(file_path)) | |
return None | |
def sort_files_by_date(directory: str): | |
"""Sort files in a directory by creation date | |
Args: | |
directory: The directory containing the files to sort | |
""" | |
for filename in os.listdir(directory): | |
file_path = os.path.join(directory, filename) | |
if os.path.isfile(file_path): | |
creation_date = get_creation_date(file_path) | |
if creation_date is None: | |
target_dir = os.path.join(directory, "unsorted") | |
else: | |
year = creation_date.strftime("%Y") | |
month = creation_date.strftime("%m") | |
target_dir = os.path.join(directory, year, month) | |
if not os.path.exists(target_dir): | |
os.makedirs(target_dir) | |
shutil.move(file_path, os.path.join(target_dir, filename)) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: python sort_files.py <directory>") | |
sys.exit(1) | |
directory = sys.argv[1] | |
sort_files_by_date(directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment