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

Time:07-04

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

CodePudding user response:

For the moment, I used terminal to append the print result to a text file:

$ python my_family.py  >> my_family.txt

any idea to do it from Python?

CodePudding user response:

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)
  • Related