I'm trying to write a function that loads all the images in a given directory and its subdirectories and returns the result as a dictionary. Here's what I have so far:
def load_all_images(path):
# TODO: Consider using os.walk() or setdefault() instead?
images = {}
contents = os.listdir(path)
dirnames = [x for x in contents if os.path.isdir(os.path.join(path, x))]
filenames = [x for x in contents if os.path.isfile(os.path.join(path, x))]
if filenames:
# This folder contains image files
basename = os.path.basename(path)
if all([re.match(r"\d+", os.path.splitext(f)[0]) for f in filenames]):
# This folder contains sequential animation frames
# (0.png, 1.png, 2.png, etc.)
images[basename] = load_images_list(path)
else:
# This folder contains named image files
images[basename] = load_images_dict(path)
# Recurse
for dirname in dirnames:
images[dirname] = load_all_images(os.path.join(path, dirname))
return images
def load_image(path):
return pygame.image.load(path).convert_alpha()
def load_images_dict(path):
images = {}
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
if not os.path.isfile(filepath):
continue
name = os.path.splitext(filename)[0]
images[name] = load_image(filepath)
return images
def load_images_list(path):
return list(load_images_dict(path).values())
Pic related shows my directory structure (above) and the actual dictionary that the function returns (below). As you can see, it's adding an extra level for some reason, and I can't figure out how to fix it. Any suggestions would be greatly appreciated.