Search code examples
pythonoperating-systemextract

How can I extract files from a folder in a specific rate? Specifically every other file?


I am using this code:

#Load original Images
org_images_path = fr"/wormbot/{lifespan_number}"
#Loop through all files in the folder
for org_image in sorted(os.listdir(org_images_path)):
    if org_image.startswith("frame"):
        image_path = os.path.join(org_images_path, org_image)
        get_image = os.path.getmtime(image_path)

to open and extract images from a folder and it works as expected. But I would like to extract every other image rather than all the images.

I've considered adding some sort of counter that goes up by two at the conclusion of each loop but I only have experience with that when using the counter to name output files so I'm not sure how that would work.


Solution

  • It is difficult to provide a concise answer without seeing your full code block but you could set a counter variable outside of your loop and then use the modulo operator % to determine whether the image is extracted and increment the counter variable on each loop.

    As an example (assuming you only want to extract every second image starting with 'frame'):

    i = 0
    for org_image in sorted(...):
        if org_image.startswith('frame'):
            if i % 2 == 0:
                image_path = ...
                get_image = ...
                ...
                i = i + 1
            else:
                i = i + 1
                continue