Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop os.walk going down further at a specific directory name

Tags:

python

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[:]
like image 567
Adam Lee Avatar asked Oct 27 '25 05:10

Adam Lee


1 Answers

From the documentation

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() 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.

like image 148
Martin Bonner supports Monica Avatar answered Oct 28 '25 18:10

Martin Bonner supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!