Is there a way to read data from a file and construct a tree using anytree?
Parent Child
A A1
A A2
A2 A21
I can do it with static values as follows. However, I want to automate this by reading the data from a file with anytree.
>>> from anytree import Node, RenderTree
>>> A = Node("A")
>>> A1 = Node("A1", parent=A)
>>> A2 = Node("A2", parent=A)
>>> A21 = Node("A21", parent=A2)
Output is
A
├── A1
└── A2
└── A21
This assumes that the entries are in such an order that a parent node was always introduced as a child of another node beforehand (root excluded).
With that in mind, we can then iterate over the lines, split them (I used
split, regex would work too) and create the new nodes.For how to get a reference to the parent by name, I came up with two solutions:
First, find the parent by name using anytrees
find_by_attrSecond, just cache them in a dict while we create them:
input.txt
Output: