Skip directories in list with os.walk?

2k views Asked by At

I have a working function that generates a list from directories of images

def jpg_descended(folder):
    matches = []
    for root, dirnames, filenames in os.walk(unicode(folder)):
        for extension in ('*.jpg', '*.jpeg', '*.png'):
            for filename in fnmatch.filter(filenames, extension):
                    matches.append(os.path.join(root, filename))
    return sorted(matches, key=os.path.getmtime, reverse=True)

but how can I get it to skip over directories I've put in a list?

excludes = ["october", "december"]

I want it to NOT return anything in directories named "october" or "december" or any other directories I may add to the excludes list.

Any and all help is appreciated.

1

There are 1 answers

0
Mark Tolonen On BEST ANSWER

You can edit dirnames in place by deleting directories that meet your requirements. when topdown=True (the default) for os.walk, that prevents those directories from being enumerated.

Make sure it is an in place edit, for example:

dirnames[:] = [dirname for dirname in dirnames if dirname not in excludes]