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 APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 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.