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
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 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.