0

I have multiple files in a folder and I want to get first four files perform some operation and get next four files perform some operation and so on. But I am unable to iterate through each file and that too in sorted manner. I tried using glob.glob but I don't know how to iterate through each file using index in glob.

My files are 0.jpg 1.jpg 2.jpg 3.jpg 4.jpg......

for image in sorted(glob.glob(directory + '*.jpg'),key=os.path.getmtime):

    name = image.split('/')[-1]
    imgname = name.split('.')[0]
Krupali Mistry
  • 624
  • 1
  • 9
  • 23
  • Did you get to the point where you have all filenames in a list? That should be the first step. Then you have to read four-by-four from that list. – zvone Apr 22 '20 at 07:29
  • I used glob so its not a list its I have edited in the question – Krupali Mistry Apr 22 '20 at 07:32
  • Does this answer your question? [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – zvone Apr 22 '20 at 07:50

1 Answers1

0

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 JPEGs). 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
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432