derkyzer
derkyzer

Reputation: 161

How do I exclude directories when using os.walk()? Other methods haven't worked

So far the following code has been nothing but stubborn:

for root,subdirs,files in os.walk(topDir):
    for fileName in files:
        if fileName.endswith(("0.tif","0.png")):
            images.update({fileName[:-5]:Image(fileName,origin)})
        elif fileName.endswith((".tif",".png")):
            try:
                images.update({fileName[:-4]:Image(fileName,picLocations[fileName[:-4]])})
            except:
                images.update({fileName[:-4]:Image(fileName,origin)})
        else:
            pass

I've tried making the first three lines read:

exclude = set(["faces","animations"])
for root,subdirs,files in os.walk(topDir):
    subdirs[:] = [d for d in subdirs if d not in exclude]

This, however, does not seem to filter out the unwanted items... am I doing something wrong??

Upvotes: 1

Views: 802

Answers (1)

Stephen Lin
Stephen Lin

Reputation: 4912

Trythis

exclude = set(["faces","animations"])
for root,subdirs,files in os.walk(topDir):
    subdirs[:] = [d for d in set(subdirs)-exclude]

Upvotes: 1

Related Questions