Efficiently removing subdirectories in dirnames from os.walk

后端 未结 2 1357
轮回少年
轮回少年 2021-01-12 11:52

On a mac in python 2.7 when walking through directories using os.walk my script goes through \'apps\' i.e. appname.app, since those are really just directories of themselves

2条回答
  •  广开言路
    2021-01-12 12:48

    You can do something like this (assuming you want to ignore directories containing '.'):

    subdirs[:] = [d for d in subdirs if '.' not in d]
    

    The slice assignment (rather than just subdirs = ...) is necessary because you need to modify the same list that os.walk is using, not create a new one.

    Note that your original code is incorrect because you modify the list while iterating over it, which is not allowed.

提交回复
热议问题