1

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??

derkyzer
  • 161
  • 1
  • 1
  • 9
  • Put a `print subdirs` before and after the `subdirs[:] =` line and see what happens. – glglgl Jul 22 '14 at 09:12
  • Do you, by any chance, use Windows and have your actual directories named in a different fashion such as `Faces` or `Animations`? Then you might want to do `subdirs[:] = [d for d in subdirs if d.lower() not in exclude]`. – glglgl Jul 22 '14 at 09:13
  • Yes, I printed them out before and after, and it appeared to be working. Yes, i am using Windows 8, but the directories are all lower case. I've gotten it sorted out for the most part now though. – derkyzer Jul 22 '14 at 09:19
  • I know this is old but check my answer to a similar question. https://stackoverflow.com/a/51871627/1896134 – JayRizzo Aug 16 '18 at 07:31

1 Answers1

1

Trythis

exclude = set(["faces","animations"])
for root,subdirs,files in os.walk(topDir):
    subdirs[:] = [d for d in set(subdirs)-exclude]
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26
  • Thanks... not sure why that worked while the other ways didn't to be honest. Now I just have to figure out why it's naming all of the images incorrectly even though they are named via their file. – derkyzer Jul 22 '14 at 09:17
  • 1
    It produces the *same* result as `subdirs[:] = [d for d in subdirs if d not in exclude]` except the order. – jfs Aug 01 '14 at 12:48
  • but, will this also _exclude_ subdirectories & files under them? – ApJo Jul 20 '23 at 21:23