Search code examples
pythonfinddepthos.walk

Python os.walk() get files before directories


I want to simulate the -depth argument of bash find command using python os.walk().

From the Linux manual page:

-depth Process each directory's contents before the directory
              itself.

How can this be done ?


Solution

  • You can use files or dirs like this:

    import os
    root_path = r'/home/testuser/test/'
    for root, dirs, files in os.walk(root_path, topdown=True):
        print(root)
        print(dirs)
        print(files)
    
    

    also you can walk through directories from bottom to top with topdown=False