January 10, 2021 will

Rendering a tree view in the terminal with Python and Rich

The latest version of Rich adds a tree view. Here's an example of one:

The labels of each branch in the tree can be text or anything else that rich can render. The guide lines can have a color per-branch and one of three styles; normal, thick, and double line.

The API to generate these trees is super simple and currently has just one public method to add a new branch.

Here's a simple example demonstrating that money does, in fact, grow on trees.

>>> from rich.tree import Tree
>>> from rich import print
>>> tree = Tree(":deciduous_tree: Money does grow on trees!")
>>> tree.add(":dollar_banknote:").add(":dollar_banknote:").add(":dollar_banknote:")
>>> print(tree)

There are many things that fit well in to a tree structure and I'm looking forward to seeing what people do with this. The most obvious application is of course displaying the contents of a filesystem. In Rich's example directory you will find tree.py which works like the linux tree command and displays the contents of a directory in a tree. In this version, the Python files are indicated by a 🐍emoji (of course).

Here's an example of the output:

An excessively colorful filesystem tree in the terminal.

If this post has left you scratching your head, Rich is my Python library for rich text and beautiful formatting in the terminal.

Follow @willmcgugan for Rich related stuff.

Use Markdown for formatting
*Italic* **Bold** `inline code` Links to [Google](http://www.google.com) > This is a quote > ```python import this ```
your comment will be previewed here
gravatar
Po Chien Yang

Awesome~

Rich is so wonderful project.

helpful to me.

gravatar
Marcio

Why don’t you create a python library focused on creating modern ui interfaces ( similar to pyqt, but more pythonic) ? You seem to have all the gears…

gravatar
Will McGugan

Where is the fun in that?

gravatar
michel_c

i used rich.tree to build the pdfalyzer a tool that gives a visual presentation of the logical structure of a PDF.

example of the condensed format

combined it with rich.panel to create really in depth tree charts... here's an example

thanks for the awesome library...

gravatar
Alex

All examples just display the tree itself. But a directory structure often has a kind of table of file information prefixed to each line: e.g. the output of exa -l --tree I wonder how that could be achieved.