Search code examples
pythonpython-3.xtreerich

How to export Tree object from Rich library to a text(.txt) file in Python?


Is there anyway to export tree object from Rich?

from rich.tree import Tree
from rich import print as rprint

tree = Tree("Family Tree")
tree.add("Mom")
tree.add("Dad")
tree.add("Brother").add("Wife")
tree.add("[red]Sister").add("[green]Husband").add("[blue]Son")

rprint(tree)

I need to export the tree as a text file from rprint(tree) result. (Ignore the colors)

enter image description here


Solution

  • rich.print uses the same syntax as print so you can write directly to an object with a write method. E.g.

    with open('my_tree.txt', 'w') as f:
        rprint(tree, file=f)