Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Generate a Beautiful Folder Tree Visualization in Python

A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.

Medium Python 3.9+ Jun 28, 2026 Files & data 2 views 0 copies

Python code

36 lines
Python 3.9+
import os
from pathlib import Path

class FolderTree:
    def __init__(self, root_path=".", ignore_list=None, max_depth=3):
        self.root = Path(root_path)
        self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
        self.max_depth = max_depth
        
    def generate(self):
        tree_lines = [f"{self.root.name}/"]
        self._add_children(self.root, "", 0, tree_lines)
        return "\n".join(tree_lines)
    
    def _add_children(self, path, prefix, depth, tree_lines):
        if depth >= self.max_depth:
            return
        try:
            items = sorted(path.iterdir(), key=lambda x: (x.is_file(), x.name))
            items = [item for item in items if item.name not in self.ignore]
            for i, item in enumerate(items):
                is_last = i == len(items) - 1
                connector = "└── " if is_last else "├── "
                tree_lines.append(f"{prefix}{connector}{item.name}")
                if item.is_dir() and depth < self.max_depth - 1:
                    extension = "    " if is_last else "│   "
                    self._add_children(item, prefix + extension, depth + 1, tree_lines)
        except PermissionError:
            tree_lines.append(f"{prefix}└── [Permission Denied]")

if __name__ == "__main__":
    import sys
    path = sys.argv[1] if len(sys.argv) > 1 else "."
    depth = int(sys.argv[2]) if len(sys.argv) > 2 else 3
    tree = FolderTree(path, max_depth=depth)
    print(tree.generate())

Output

stdout
myproject/
├── README.md
├── src/
│   ├── __init__.py
│   ├── main.py
│   └── utils.py
└── tests/
    ├── __init__.py
    └── test_main.py

How it works

The FolderTree class uses Path.iterdir() with sorting so directories appear before files, creating a clear visual hierarchy. The private _add_children method builds the tree recursively, adding tree-drawing characters (like "├──" and "└──") and indentation prefixes to mimic standard Unix tree output. Ignored folders (common cache and version control directories) are skipped to keep the display clean. Permission errors are gracefully caught and shown as a placeholder instead of crashing.

Common mistakes

  • Forgetting to handle `PermissionError` on restricted directories, which would crash the script.
  • Using the same prefix for all items regardless of nesting level, breaking the tree layout.
  • Not sorting items, so the tree appears in arbitrary filesystem order.
  • Setting `max_depth` too low, resulting in an empty or incomplete tree.

Variations

  1. Use `os.walk` with manual indentation for an alternate implementation.
  2. Include file sizes by calling `os.path.getsize` inside the recursion.

Real-world use cases

  • Documenting project structure in README or onboarding guides without manual typing.
  • Generating folder snapshots for audit logs or deployment checklists.
  • Building a quick CLI overview of a complex nested data directory during debugging.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.