Skip to content

Instantly share code, notes, and snippets.

@JVT038
Created May 2, 2022 14:47
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 JVT038/17d1642f5e31963555a96a1127e7c0d9 to your computer and use it in GitHub Desktop.
Save JVT038/17d1642f5e31963555a96a1127e7c0d9 to your computer and use it in GitHub Desktop.
A script to organize media into different folders based on year and month

This python script I wrote has been made to organize (thousands of) photos in the same directory into different folders, depending on year, and month. This can be useful if you use (or have used) the OneDrive syncing app, where all the photos will be synced into one big folder called the 'Camera Roll'.

Feel free to modify this script to your own purposes. Warning: This script isn't perfect. It can lead to errors, conflicts, it can malfunction. If something goes wrong, I am not responsible, though your data should be 100% safe, as nothing gets deleted, only moved.

The following python packages are required to run this script: ffmpeg-python exif dateutil

import os
import ffmpeg
from ffmpeg import Error
from shutil import move
from dateutil.parser import parse
from datetime import datetime
from exif import Image
path = input('Enter path to folder: ')
counter = 0
def createdirs (date, filepath):
try:
dir = os.path.join(path, str(date.year).zfill(2), str(date.month).zfill(2))
os.makedirs(dir, 0O775, exist_ok=True)
move(filepath, os.path.join(dir, file))
print(f'{filepath} moved to {dir}')
counter + 1
except Exception as e:
print(e)
def lastmodified(filepath):
print(f'File {filepath} does not contain correct metadata, resorting to last modified date...')
lastmodified = os.stat(filepath).st_mtime
if lastmodified < 0:
print(f'File {filepath} does not contain a correct date either, ignoring...')
return False
date = datetime.fromtimestamp(lastmodified)
createdirs(date, filepath)
if os.path.exists(path) and os.path.isdir(path):
files = os.listdir(path)
for file in files:
filepath = os.path.join(path, file)
extension = file.split('.')[len(file.split('.')) - 1].upper()
if extension in ['JPG', 'JPEG']:
image = open(filepath, 'rb')
try:
exif_data = Image(image)
image.close()
if exif_data.has_exif and hasattr(exif_data, 'datetime'):
date = parse(exif_data.datetime[0:10].replace(':', '-'))
createdirs(date, filepath)
else:
lastmodified(filepath)
except:
image.close()
lastmodified(filepath)
elif extension in ['MP4']:
try:
video = ffmpeg.probe(filepath)
try:
creation_time = video["streams"][0]["tags"]["creation_time"]
date = parse(creation_time)
createdirs(date, filepath)
except KeyError:
lastmodified(filepath)
except Error as e:
print(e)
elif extension in ['GIF', 'PNG']:
lastmodified(filepath)
print(f'Finished moving {counter} files')
else:
print('Error: Path does not exist or is not a directory')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment