Skip to content

Instantly share code, notes, and snippets.

@luxcem
Created May 21, 2017 18:38
Show Gist options
  • Save luxcem/49609fdfb109e75597935d1591795c86 to your computer and use it in GitHub Desktop.
Save luxcem/49609fdfb109e75597935d1591795c86 to your computer and use it in GitHub Desktop.
# encoding: utf-8
import os
import argparse
import exifread
from path import path
import dateutil.parser
def main():
parser = argparse.ArgumentParser(description='Archive image based on time photo was taken.')
parser.add_argument('src', help='Source directory')
parser.add_argument('dst', help='Destination directory')
args = parser.parse_args()
if args.src[-1] == '/':
del args.src[-1]
if args.dst[-1] == '/':
del args.dst[-1]
for f in path('{}/.'.format(args.src)).walkfiles():
filename = os.path.basename(f)
img = open(f, 'rb')
# Return Exif tags
tags = exifread.process_file(img)
try:
file_date = tags['EXIF DateTimeOriginal']
file_date = str(file_date).split(' ')[0].replace(':', '/')
dt = dateutil.parser.parse(str(file_date))
directory = '{dst}/{year}/{month}'.format(dst=args.dst, year=dt.year, month=dt.month)
except KeyError:
directory = '{dst}/unknown'.format(dst=args.dst)
if not os.path.isdir(directory):
os.makedirs(directory)
destination = '{}/{}'.format(directory, filename)
i = 2
while os.path.isfile(destination):
destination = '{directory}/{basefilename}_{i}{ext}'.format(
directory = directory,
basefilename = os.path.splitext(filename)[0],
i = i,
ext = os.path.splitext(filename)[1]
)
i += 1
os.rename(f, destination)
print('{} -> {}'.format(f, destination))
main()
@luxcem
Copy link
Author

luxcem commented May 21, 2017

This code organise photos in folders and subfolders depending on time the photo was taken. Great to (re)organise a big picture library. It take care to not remove file on destination and rather create duplicates.

TODO

  • Instead of create a duplicate, check file hash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment