Created
September 8, 2019 22:21
-
-
Save DarthJahus/afdc5070a877d3033f4005ec8e7f4e51 to your computer and use it in GitHub Desktop.
Read EXIF data from image and video files and sort theses files in a custom structure (folders and subfolders representing years, months and days…).
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
from PIL import ExifTags, Image | |
from os import listdir, mkdir | |
from os.path import isfile, join, isdir, getmtime | |
from datetime import datetime | |
import shutil | |
files = [f for f in listdir('.') if isfile(join('.', f))] | |
__folder_structure = ["%Y", "%Y-%m (%Y-%B)", "%Y-%m-%d"] | |
for file in files: | |
_datetime = None | |
if file[-4:].lower() == ".jpg" or file[-5:].lower() == ".jpeg": | |
try: | |
image = Image.open(file) | |
exif_data = { | |
ExifTags.TAGS[k]: v for k, v in image._getexif().items() if k in ExifTags.TAGS | |
} | |
image.close() # Release image file | |
if "DateTimeOriginal" in exif_data: | |
_datetime = exif_data["DateTimeOriginal"] | |
_datetime = datetime.strptime(_datetime, "%Y:%m:%d %H:%M:%S") | |
elif "DateTimeDigitized" in exif_data: | |
_datetime = exif_data["DateTimeDigitized"] | |
_datetime = datetime.strptime(_datetime, "%Y:%m:%d %H:%M:%S") | |
except: | |
print("Error reading file '%s'" % file) | |
elif file[-4:].lower() == ".mp4": | |
try: | |
_datetime = datetime.fromtimestamp(int(getmtime(join('.', file)))) | |
except: | |
print("Error reading file '%s'" % file) | |
elif file[-3:].lower() == ".py": | |
continue | |
elif file[-3:].lower() != ".py": | |
try: | |
_datetime = datetime.fromtimestamp(int(getmtime(join('.', file)))) | |
except: | |
print("Error reading file '%s'" % file) | |
if _datetime is not None: | |
_current = "." | |
for _structure in __folder_structure: | |
_folder = datetime.strftime(_datetime, _structure) | |
if not isdir(join(_current, _folder)): | |
mkdir(join(_current, _folder)) | |
print("Directory '%s' created" % _folder) | |
else: | |
pass | |
_current = join(_current, _folder) | |
shutil.move(join('.', file), join(_current, file)) | |
else: | |
print("File has no datetime tag: '%s'" % file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment