1

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.

dxrth
  • 33
  • 7
  • Possible duplicate of [How do I exclude directories when using os.walk()? Other methods haven't worked](http://stackoverflow.com/questions/24883084/how-do-i-exclude-directories-when-using-os-walk-other-methods-havent-worked) – Stephen Rauch Dec 31 '16 at 19:05

1 Answers1

3

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]
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251