1

I have a tree structure stored in a text file. I want to read the file into Python and convert it into a Node object.

The standard way to build the tree is as follows:

from zss import Node

A = (
    Node("+") 
        .addkid(Node("+") 
            .addkid(Node("2")) 
            .addkid(Node("4")))
        .addkid(Node("*") 
            .addkid(Node("3")) 
            .addkid(Node("5"))) 
    )

Now I have the structure stored in a text file. e.g. A.txt

Node("+")
        .addkid(Node("+")
            .addkid(Node("2"))
            .addkid(Node("4")))
        .addkid(Node("*")
            .addkid(Node("3"))
            .addkid(Node("5")))

Is there a way to read A.txt into python as an object of class Node? I tried converting the file into a .py file and reading in however it was not successful?

SriniShine
  • 1,089
  • 5
  • 26
  • 46
  • 2
    https://docs.python.org/3/library/pickle.html ? – G_M Feb 22 '18 at 19:39
  • 1
    Yeah, pickling it doesn't seem like such a bad idea. Storing the Python code in a text file seems kind of weird. I guess you could `eval` its contents (at your own risk). – pushkin Feb 22 '18 at 19:40
  • 1
    @DeliriousLettuce Thank you. I think pickle would do the job. – SriniShine Feb 22 '18 at 19:57
  • Possible duplicate of [how to save/read class wholly in Python](https://stackoverflow.com/questions/2345151/how-to-save-read-class-wholly-in-python) – Georgy Feb 22 '18 at 20:01

0 Answers0