import glob import PIL.Image import os x = 2 photos = glob.glob(f'photos/{x}/*.jpg') for image in photos: print(image) img = PIL.Image.open(image) big_image = image.replace('.jpg', '.webp') if os.path.exists(big_image): continue img.save(big_image) ratio = 400/max(img.height, img.width) img = img.resize((int(img.width * ratio), int(img.height * ratio))) small_image = image.replace(f'photos/{x}/', f'photos/{x}/thumbnail/').replace('.jpg', '.webp') if os.path.exists(small_image): continue img.save(small_image, quality=50, subsampling=2)