Last active
May 18, 2022 03:15
-
-
Save guychouk/0cb1a7d92713b54d88bc09ed00e08272 to your computer and use it in GitHub Desktop.
Python script for sorting images and videos by Years and Months based on EXIF & Media Created Info.
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
''' | |
Put this script in a messy folder filled with images and video files. | |
After running it, a "Years" folder will be created with the media files | |
sorted by months in each year. | |
You can also change what types of files to look for in your folder by | |
adding to or changing the "imgFormats" and "videoFormats" lists. | |
''' | |
import os | |
from datetime import datetime | |
from PIL import Image | |
from PIL.ExifTags import TAGS | |
from hachoir.parser import createParser | |
from hachoir.metadata import extractMetadata | |
DATE_TIME_ORIG_TAG = 36867 | |
DELETE = False | |
imgFormats = ['png', 'jpg', 'jpeg'] | |
videoFormats = ['m4v', 'mov', 'mp4'] | |
for afile in os.listdir(): | |
filename = os.fsdecode(afile) | |
print("Processing %s\n" % filename) | |
name = filename.split('.')[0] | |
if os.path.isdir(filename): | |
continue | |
elif filename.endswith(".py"): | |
continue | |
elif filename.split('.')[1].lower() in imgFormats: | |
try: | |
im = Image.open(afile) | |
exif = im._getexif() | |
im.close() | |
if DATE_TIME_ORIG_TAG in exif: | |
print("Has EXIF: %s\n" % exif[DATE_TIME_ORIG_TAG]) | |
datestr = exif[DATE_TIME_ORIG_TAG].split() | |
dateobj = datetime.strptime(datestr[0], "%Y:%m:%d") | |
dirpath = "Years/%s/%s/" % (dateobj.year, dateobj.month) | |
os.makedirs(dirpath, exist_ok=True) | |
os.rename(filename, dirpath + filename) | |
continue | |
except: | |
continue | |
elif filename.split('.')[1].lower() in videoFormats: | |
parser = createParser(filename) | |
if not parser: | |
print("Unable to parse file %s" % filename) | |
continue | |
with parser: | |
try: | |
metadata = extractMetadata(parser) | |
except Exception as err: | |
print("Metadata extraction error: %s" % err) | |
metadata = None | |
if not metadata: | |
print("Unable to extract metadata") | |
continue | |
for line in metadata.exportPlaintext(): | |
if line.split(':')[0] == '- Creation date': | |
dateobj = datetime.strptime(line.split(':')[1].split()[0], "%Y-%m-%d") | |
dirpath = "Years/%s/%s/" % (dateobj.year, dateobj.month) | |
os.makedirs(dirpath, exist_ok=True) | |
os.rename(filename, dirpath + filename) |
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
hachoir | |
Pillow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment