Created
March 3, 2020 16:09
-
-
Save anabarasan/06bd481addaae340d4e49c78a7504cfb to your computer and use it in GitHub Desktop.
organize photos by `year/month/day/file` folder struction based on EXIF data
This file contains 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
#!/usr/bin/env python3 | |
from os import listdir | |
from os.path import dirname, exists, isfile, join | |
from pathlib import Path | |
import shutil | |
import sys | |
from PIL import ExifTags, Image, UnidentifiedImageError | |
def print_exif_info(img): | |
data = {} | |
for k, v in img._getexif().items(): | |
if k in ExifTags.TAGS: | |
data[ExifTags.TAGS[k]] = v | |
else: | |
data[k] = v | |
return data | |
def check_and_create_directory(file_path): | |
dir_name = dirname(file_path) | |
Path(dir_name).mkdir(parents=True, exist_ok=True) | |
def move(source, destination): | |
check_and_create_directory(destination) | |
shutil.move(source, destination) | |
def main(): | |
files_path = sys.argv[1] | |
files = sorted([f for f in listdir(files_path) | |
if isfile(join(files_path, f))]) | |
for file_ in files: | |
img_file = join(files_path, file_) | |
try: | |
img = Image.open(img_file) | |
exif_data = print_exif_info(img) | |
date = exif_data.get('DateTimeOriginal') | |
if date: | |
date = date.split()[0] | |
year, month, day = date.split(':') | |
out_path = join(files_path, year, month, day, file_) | |
print(f'moving {img_file} to {out_path}') | |
move(img_file, out_path) | |
except UnidentifiedImageError: | |
print(f'Error handling {img_file}') | |
print('*' * 80) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment