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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursion mirrors a tree's shape: each directory re-invokes the same function on its children.
- 2Passing an accumulated prefix down the call stack lets each level draw its own indentation correctly.
- 3Sorting by a tuple key groups directories before files while keeping each group alphabetical.
Related explainers
python
import argparse import sys from pathlib import Path
Building a subcommand CLI with argparse
cli
argparse
subcommands
Intermediate
6 steps
python
from collections.abc import Mapping from typing import Any, Iterator
Flattening nested config into dotted keys
recursion
generators
tree-traversal
Intermediate
7 steps
python
import csv import io from datetime import datetime
Streaming a CSV export in Flask
streaming
generators
csv
Intermediate
9 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
Intermediate
7 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
python
from django.conf import settings from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.db.models.signals import post_save
Sending a welcome email with Django signals
signals
email
user-activation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/printing-a-directory-tree-with-recursion-explained-python-b973/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.