Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To retrieve the size and path of images located in a directory, excluding specific subfolders, using recursion, we can use the following steps:

  1. Define a function that takes a directory path as input.
  2. Within the function, use the os module to get a list of all files and directories within the input directory.
  3. Iterate over the list of files and directories, filtering out directories that should be excluded.
  4. For each file found, check if it is an image file (e.g. using the file extension). If it is, add its size and path to a list.
  5. If a directory is found, recursively call the function with that directory path as input.
  6. Return the list of image file sizes and paths.

Here is a sample code:

import os from PIL import Image

def getimagesizes(path, excludedfolders=[]): files = os.listdir(path) imagesizes = [] for file in files: filepath = os.path.join(path, file) if os.path.isdir(filepath) and file not in excludedfolders: # recursively call the function for subdirectories imagesizes.extend(getimagesizes(filepath, excludedfolders)) elif os.path.isfile(filepath) and file.lower().endswith(('.jpg', '.jpeg', '.png')): try: img = Image.open(filepath) imagesizes.append({ 'path': filepath, 'size': img.size }) img.close() except: pass return image_sizes

usage example

path = '/path/to/directory' excludedfolders = ['subfolder1', 'subfolder2'] imagesizes = getimagesizes(path, excludedfolders) print(imagesizes)