Ask Your Question
1

How can we retrieve the size and path of images located in a directory, excluding specific subfolders, using recursion?

asked 2023-07-16 13:31:30 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-16 13:47:02 +0000

pufferfish gravatar image

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)

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-16 13:31:30 +0000

Seen: 12 times

Last updated: Jul 16 '23