Search code examples
pythonos.walksubdirectory

Os.walk() alternatives


I'm writing a program that needs to explore all possible subdirectories of a given path topdown. My problem is that I need to do things before calling recursion and after finish recursion and os.walk() doesn't allow this. More precisely the recursion in the directories subtree that I need is:

(Note: is not real Python code, just Python-like code to explain what I need to do)

def recursion(path):
    action1()
   for subdir in path:
       recursion(path+subdir)
   action2()

while what I can do with os.walk() is simply:

def recursion(path):
    action1()
    action2()
    for subdir in path:
        recursion(path+subdir)

Is there any solution?


Solution

  • You can use os.scandir instead:

    def recursion(path):
        action1()
        for entry in os.scandir(path):
            if entry.is_dir():
                recursion(os.path.join(path, entry.name))
        action2()
    

    or if you're using Python 3.4 or earlier versions, use the slower os.listdir instead:

    def recursion(path):
        action1()
        for name in os.listdir(path):
            full_path = os.path.join(path, name)
            if os.path.isdir(full_path):
                recursion(full_path)
        action2()