Skip to content

Instantly share code, notes, and snippets.

@fogside
Created March 25, 2017 22:21
Show Gist options
  • Save fogside/4def2be8f38e43d98e2151917848e42b to your computer and use it in GitHub Desktop.
Save fogside/4def2be8f38e43d98e2151917848e42b to your computer and use it in GitHub Desktop.
import os
src_path = '/Users/fogside/Desktop/all_photos/Camera/'
dst_path = '/Users/fogside/Desktop/all_photos/'
###############################################################################################
##### Creating folders like <year-month> in dst_path ######################################
##### and moving photos from all folders in the src_path ######################################
##### to the corresponding folder <year-month> ######################################
##### filenames must be like: ######################################
##### >> *_20161204_*.jpg or ######################################
##### >> *_2015-10-31_*.jpg ######################################
###############################################################################################
def process_photo(filename):
tmp = filename.split('_')
if len(tmp[1])==8:
year = int(tmp[1][:4])
month = int(tmp[1][4:6])
else:
tmp = tmp[1].split('-')
year = int(tmp[0])
month = int(tmp[1])
return year, month
list_of_files = {}
for (dirpath, dirnames, filenames) in os.walk(src_path):
for filename in filenames:
if filename.endswith('.jpg'):
year, month = process_photo(filename)
filename = os.path.join(dirpath, filename)
if year in list_of_files.keys():
if month in list_of_files[year].keys():
list_of_files[year][month].append(filename)
else:
list_of_files[year][month] = [filename]
else:
list_of_files[year] = {month:[filename]}
###########################################################################################
##### moving photos to the corresponding folders ##########################################
###########################################################################################
for year in list_of_files.keys():
for month in list_of_files[year].keys():
new_dir = os.path.join(dst_path, '{}-{}'.format(year, month))
if not os.path.isdir(new_dir):
os.mkdir(new_dir)
for filename in list_of_files[year][month]:
new_name = os.path.join(new_dir, filename.split('/')[-1])
if not os.path.exists(new_name):
os.rename(filename, new_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment