Here's a way of doing it. I see you have another question nearly the same, and you are likely going to need a "fill" value in case your directory has a number of images that is not an exact multiple of 4. I suggest you create a "fill" image (as a PNG
so that it doesn't appear in your sorted list of JPEG
s). Make the "fill" image the same colour as the background onto which you paste the other 4 images so that it doesn't even show up.
#!/usr/bin/env python3
import os, glob
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"""
Group items of list in groups of "n" padding with "fillvalue"
"""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
# Go to where the images are instead of managing a load of paths
os.chdir('images')
# Get list of filenames sorted by mtime
filenames = sorted(glob.glob('*.jpg'),key=os.path.getmtime)
# Iterate over the files in groups of 4
for f1, f2, f3, f4 in grouper(filenames, 4, 'fill.png'):
print(f1,f2,f3,f4)
Sample Output
iphone.jpg door.jpg hands.jpg solar.jpg
test.jpg circuit_board.jpg r1.jpg r2.jpg
thing.jpg roadhog.jpg colorwheel.jpg hogtemplate.jpg
tiger.jpg bean.jpg image.jpg bottle.jpg
result.jpg fill.png fill.png fill.png