Skip to content

Instantly share code, notes, and snippets.

@arav97531
Last active February 20, 2018 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arav97531/d17044aee1a188853be2 to your computer and use it in GitHub Desktop.
Save arav97531/d17044aee1a188853be2 to your computer and use it in GitHub Desktop.
Maybe most useful of all the scripts I made. Written to sort the photos of my cat, about 3 years ago, and all this time I kept modifying it, but I think it's finally done. :3
#!/bin/env python3
"""Sort Media Files By Date
A script sorts the files using a date from an EXIF field, or a file name.
Adapted for YYYY-MM-DD date formats. A regexp is simple to alter.
A set of extensions that must be sorted can be easily changed by modifying of
a tuple ALLOWEDFORMATS.
Script builds a directory structure where it was ran.
Directory structure:
YYYY
|--MM
|--DD
Example:
2016
|--02
|--27
|--files...
|--07
|--14
|--files...
|--26
|--files...
The script uses a library Pillow.
"""
__version__ = "2.1.0"
__author__ = "Arav"
__email__ = "arav@tfwno.gf"
__copyright__ = "Copyright © 2014-2018 Arav <arav@tfwno.gf>"
__license__ = """
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
"""
from os import listdir, makedirs
from os.path import join, exists
from re import match
from shutil import move
from sys import argv
from PIL import ExifTags, Image
EXIF_TAG_DATETIME = "DateTime"
REGEXP = r".+(?P<year>\d{4})[-:]?(?P<month>\d{2})[-:]?(?P<day>\d{2}).+", # YYYY(-:)MM(-:)DD
ALLOWED_FORMATS = (
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", \
".mp4", ".3gp"
)
def get_exif_field(data, field):
"""Return given field's value."""
return [v for (k, v) in data.items() if ExifTags.TAGS.get(k) == field][0]
def main():
directory = argv[1] if len(argv) > 1 else quit()
for file in listdir(directory):
if not file.lower().endswith(ALLOWED_FORMATS):
continue
file = join(directory, file)
try:
exifdata = Image.open(file)._getexif()
date = get_exif_field(exifdata, EXIF_TAG_DATETIME)
year, month, date = date.split()[0].split(":")
except OSError:
re_res = match(REGEXP, file)
if re_res:
year, month, date = re_res.group('year'), re_res.group('month'), \
re_res.group('day')
else:
continue
destination_directory = join(directory, year, month, date)
makedirs(destination_directory, exist_ok=True)
print("Moving file {}... ".format(file), end="")
move(file, destination_directory)
print("Done.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment