[Tutor] iterating through a directory

Alan Gauld alan.gauld at btinternet.com
Wed Sep 9 18:36:22 CEST 2015


On 09/09/15 15:29, richard kappler wrote:

> Still not sure how to efficiently get the script to keep moving to the next
> file in the directory though, in other words, for each iteration in the
> loop, I want it to fetch, rename and send/save the next image in line. Hope
> that brings better understanding.

Sounds like you want a circular list.

The traditional way to generate a circular
index into a list is to use the modulo (%) operator

But the itertools module gives you a better option with
the cycle function:

import itertools as it

for img in it.cycle(os.listdir(my_img_path)):
     process(img)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list