[Solved] Why my recursion doesn’t work in os.listdir(), it doesn’t go to the lower level of a folder


Your problem stems from poorly thought out and/or formatted path strings. Instead of concatenating raw strings, use os.path.join(). And make sure you’re always passing absolute paths. In that same vein, using string methods directly instead of “+” is often more efficient and usually more readable. With those in mind, working code:

import os

def rec(direc, pre):
    for item in os.listdir(direc):
        checkpath = os.path.join(direc, item)
        if os.path.isfile(checkpath):
            print('{}{}\n'.format(pre, item))
        elif os.path.isdir(checkpath):
            print('{}{}\n'.format(pre, item))
            rec(checkpath, '{}---'.format(pre))

rec('.', '-')

Be warned: os.path.isdir() follows symbolic links, so you could end up in an infinite recursion situation. Check for os.path.islink() if you don’t need to follow links and want to avoid this situation.

1

solved Why my recursion doesn’t work in os.listdir(), it doesn’t go to the lower level of a folder