python 24 lines · 6 steps

Printing a directory tree with recursion

A recursive walk renders a filesystem tree with the box-drawing connectors you see in the `tree` command.

Explained by highlit
1from pathlib import Path
2 
3 
4def print_tree(root, prefix="", show_hidden=False):
5 root = Path(root)
6 entries = sorted(
7 (p for p in root.iterdir() if show_hidden or not p.name.startswith(".")),
8 key=lambda p: (p.is_file(), p.name.lower()),
9 )
10 
11 for index, entry in enumerate(entries):
12 is_last = index == len(entries) - 1
13 connector = "└── " if is_last else "├── "
14 print(f"{prefix}{connector}{entry.name}{'/' if entry.is_dir() else ''}")
15 
16 if entry.is_dir():
17 extension = " " if is_last else ""
18 print_tree(entry, prefix + extension, show_hidden)
19 
20 
21def render_tree(root, show_hidden=False):
22 root = Path(root)
23 print(f"{root.name or root}/")
24 print_tree(root, show_hidden=show_hidden)
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion mirrors a tree's shape: each directory re-invokes the same function on its children.
  2. 2Passing an accumulated prefix down the call stack lets each level draw its own indentation correctly.
  3. 3Sorting by a tuple key groups directories before files while keeping each group alphabetical.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Printing a directory tree with recursion — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code