Recursion — Scanning Nested Directories

20 min In Progress

Learning Objectives

  • Explain what recursion is and why it needs a base case
  • Write a recursive directory scanner
  • Compare recursion vs iteration — know the trade-offs

What Recursion Is

A recursive function calls itself to solve a smaller version of the same problem. Every recursive function needs two things: (1) a base case — when to stop, and (2) a recursive case — calling itself with a smaller input. Forget the base case and Python raises RecursionError.

def countdown(n):
    if n == 0:           # base case
        print("Done!")
        return
    print(n)
    countdown(n - 1)     # recursive case

countdown(5)

Recursive Directory Scanner — Real Security Use

Malware hides in deeply nested directories. A recursive scanner handles any depth automatically — you don't need to know how deep the tree goes. This pattern is used in forensic tools and AV scanners.

Run this locally — it scans your actual filesystem from the current directory.
import os

def scan_directory(path, depth=0):
    indent = "  " * depth
    try:
        for entry in os.scandir(path):
            print(f"{indent}{entry.name}")
            if entry.is_dir():
                scan_directory(entry.path, depth + 1)
    except PermissionError:
        print(f"{indent}[permission denied]")

scan_directory(".")

Recursion vs Iteration — The Real Trade-off

Advantage: clean code for tree-like structures, handles unlimited depth. Disadvantage: each call uses stack memory. Python's default limit is 1000 calls. Very deep trees crash with RecursionError. For unknown-depth trees in production, use an iterative stack instead.

import sys
print(sys.getrecursionlimit())  # 1000

# Iterative alternative — safer for very deep trees
import os

def scan_iterative(start_path):
    stack = [start_path]
    while stack:
        current = stack.pop()
        print(current)
        try:
            for entry in os.scandir(current):
                if entry.is_dir():
                    stack.append(entry.path)
        except PermissionError:
            pass

scan_iterative(".")

📝 Exercise: Recursive File Counter

Write a recursive function count_files(path) that returns the total number of files (not directories) inside a directory and all its subdirectories.

code.py
Output

            
← Back to Chapter