2 min read

Directory Tree Visualizer

This utility visualizes the file structure of a directory in a tree-like format directly in the terminal. It demonstrates recursion and file system traversal using the modern pathlib module.

Modules Used:

  • pathlib: To traverse directories and handle paths object-orientedly.
  • argparse: To handle the input directory argument.

The Code

Save this as tree.py.

import argparse
from pathlib import Path

def print_tree(directory, prefix=""):
    path = Path(directory)

    # Get all items in directory
    try:
        # Sort items: directories first, then files, both alphabetically
        items = sorted(list(path.iterdir()), key=lambda x: (not x.is_dir(), x.name.lower()))
    except PermissionError:
        print(f"{prefix}[Access Denied]")
        return

    # Tree connectors
    space =  "    "
    branch = "│   "
    tee =    "├── "
    last =   "└── "

    count = len(items)

    for i, item in enumerate(items):
        is_last = (i == count - 1)

        connector = last if is_last else tee

        print(f"{prefix}{connector}{item.name}")

        if item.is_dir():
            extension = space if is_last else branch
            print_tree(item, prefix + extension)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Directory Tree Visualizer")
    parser.add_argument("directory", nargs="?", default=".", help="Directory to visualize (default: current)")

    args = parser.parse_args()

    root = Path(args.directory)
    if not root.exists():
        print(f"Error: {root} does not exist.")
    else:
        print(root.resolve().name or str(root.resolve()))
        print_tree(root)

Usage

python tree.py ./my_project

programming/python/python