Skip to content

Instantly share code, notes, and snippets.

@MathijsdeBoer
Last active November 30, 2019 16:02
Show Gist options
  • Save MathijsdeBoer/fb9711a40f77a73253828a6340e96c11 to your computer and use it in GitHub Desktop.
Save MathijsdeBoer/fb9711a40f77a73253828a6340e96c11 to your computer and use it in GitHub Desktop.
Quickly sort all photos (or files) by modification dates in subdirectories
from __future__ import print_function, division
import os
import shutil
import time
count = 0
unsortable_directory = "unsorted"
print("Sort Photos")
files = [f for f in os.listdir(".") if os.path.isfile(f)]
# Do not count this script in the total count
total = len(files) - 1
for f in files:
if not str(f).endswith(".py"):
print(f"{count}/{total}: {f}", end='\r')
date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(f)))
# Make sure the directory exists
if not os.path.exists(date):
os.makedirs(date)
# In Windows, if a file already exists in the destination directory, an exception will be thrown
try:
shutil.move(f, date)
except shutil.Error:
if not os.path.exists(unsortable_directory):
os.makedirs(unsortable_directory)
# If even then the file already exists in the unsortable directory, we can delete
try:
shutil.move(f, unsortable_directory)
except shutil.Error:
os.remove(f)
count += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment