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.