In this tutorial, I will show you how easily we can show directory in Tree structure view in Python.
Here is the code:
from pathlib import Path # Define the tree components space = ' ' branch = '│ ' tee = '├── ' last = '└── ' def tree(directory: Path, prefix: str = ''): """ A recursive generator to yield a visual tree structure line by line for a given directory Path object, each line prefixed appropriately. """ contents = list(directory.iterdir()) pointers = [tee] * (len(contents) - 1) + [last] for pointer, path in zip(pointers, contents): yield prefix + pointer + path.name if path.is_dir(): extension = branch if pointer == tee else space yield from tree(path, prefix=prefix+extension) # Call the function and print each line for line in tree(Path.home()): print(line)
If you wish you can change the root directory like this:
for line in tree(Path.home() / 'foldername_here'): print(line)
Output:

Explanation:
space = ' '
branch = '│ '
tee = '├── '
last = '└── '
These lines define string variables that will be used to create the visual parts of our tree structure. They represent the spaces and branch symbols of the tree.
def tree(directory: Path, prefix: str = ''):
Here, we define a function named tree
that takes two parameters: directory
, which is a Path
object representing the directory we want to display, and prefix
, which is a string used to format the tree structure.
contents = list(directory.iterdir())
This line lists all items in the given directory. directory.iterdir()
returns an iterator over the items in the directory, and we convert it into a list.
pointers = [tee] * (len(contents) - 1) + [last]
Here, we create a list of pointers (tee
and last
) that will visually connect the items in the tree. For all items except the last one, we use tee
. For the last item, we use last
.
Then in the for loop, for each item in the directory, we yield a line that combines the prefix
, pointer
, and the item name. If the item is a directory, we recursively call tree
to list its contents, updating the prefix
to maintain the correct visual structure.