Computer >> Computer tutorials >  >> Programming >> Python

How to list directory tree structure in python?


You can use the os.walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.

For example

import os
def tree_printer(root):
    for root, dirs, files in os.walk(root):
        for d in dirs:
            print os.path.join(root, d)    
        for f in files:
            print os.path.join(root, f)
tree_printer('.')

This will print a list of all the directories in your tree first and the print the paths of all the files in the directory recursively.

For example

C:\hello\my_folder
C:\hello\another_folder
C:\hello\my_folder\abc.txt
C:\hello\my_folder\xyz.txt
C:\hello\another_folder\new.txt
...