Skip to content

Instantly share code, notes, and snippets.

@bcjarrett
Created March 1, 2019 16:33
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 bcjarrett/eac5706199ddb645fbdf6a0d63a48f27 to your computer and use it in GitHub Desktop.
Save bcjarrett/eac5706199ddb645fbdf6a0d63a48f27 to your computer and use it in GitHub Desktop.
Recursively consolidates .TIF and .JPG images into a single directory with file names based on folder names
import glob
import os
import pathlib
import ntpath
import shutil
if __name__ == '__main__':
def get_image_files(_dir):
tif = glob.glob(f'{_dir}/**/*.tif', recursive=True)
jpg = glob.glob(f'{_dir}/**/*.jpg', recursive=True)
return tif + jpg
def parent_folder_names(base_folder, _file):
_file_split = _file.split('\\')
_folder_split = base_folder.split('\\')
return _file_split[len(_folder_split): len(_file_split) - 1]
working_dir = os.path.dirname(os.path.realpath(__file__))
new_folder_of_images = 'consolidated_images'
# Generate unique list of images in the image dir and all the subdirectories
images = get_image_files(working_dir)
con_folder = f'{working_dir}\\{new_folder_of_images}'
pathlib.Path(f'{con_folder}').mkdir(parents=True, exist_ok=True)
# Rename images with our folder naming convention
for image in images:
_ = '_'.join(parent_folder_names(working_dir, image))
img_name = _ + '_' + ntpath.basename(image) if _ else ntpath.basename(image)
print(f'{image} -> {con_folder}\\{img_name}')
shutil.copyfile(image, f'{con_folder}\\{img_name}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment