Search code examples
pythonrecursionprintingpathname

Print the pathnames of folders and their subfolder recursively


I'm trying to print the pathnames of every file and its subfolders in a folder
This is the code I have so far:

def traverse(path, d):
    for item in os.listdir(path):
        item = os.path.join(path, d)
        try:
            traverse(path,d)
        except:
            print(path)

Solution

  • You're looking for os.walk.

    You can use it something like:

    def traverse(path):
        for root, dirs, files in os.walk(path):
            print(root)
    
            # if you want files too: 
            for f in files: 
                print(os.path.join(root, f))