Reputation: 3003
I need to stop os.walk from going down further if the path contains both "release" and "arm-linux". I have a bunch of these at different levels of directories. So I can't simply dictate the level. So far I have the following and it unnecessarily dive past directories in 'arm-linux'.
def main(argv):
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
if "release" and "arm-linux" in path:
print(os.path.abspath(root))
getSharedLib(argv)
[update] This is my solution
def main(argv):
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
if "release" in path and "arm-linux" in path:
print(os.path.abspath(root))
getSharedLib(argv)
del dirs[:]
Upvotes: 4
Views: 669
Reputation: 28987
From the documentation
When topdown is True, the caller can modify the dirnames list in-place (perhaps using
del
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames;
Note that topdown is True by default.
Edit
To delete all the elements of dirs
, you will need something like del dirs[:]
. That will delete all the elements of the list object that is referred to as dirs
in your code, but is referred to by another name in the os.walk
code.
Just using del dirs
will stop dirs
in your code from referring to the list, but won't do anything to the os.walk
reference. Similarly dirs = []
will replace what dirs
in your code refers to, but won't affect os.walk
code.
Upvotes: 8