jjkparker
jjkparker

Reputation: 30567

Reading object tree from file into Python

I have a Python app that contains an object structure that the user can manipulate. What I want to do is allow the user to create a file declaring how the object structure should be created.

For example, I would like the user to be able to create the following file:

foo.bar.baz = true
x.y.z = 12

and for my app to then create that object tree automatically. What's the best way to do something like this?

Upvotes: 1

Views: 264

Answers (1)

Jon W
Jon W

Reputation: 15816

Typically problems like this one are solved with XML. However in your case you can do something even easier.

Assuming the dots represent hierarchy delimiters, you could read in the left hand side of the = sign (input.split('=')[0]), and then perform a split('.') on the dots. Next, create a nested dictionary structure to match this. i.e. object[foo][bar][baz] returns True and object[x][y][z] returns 12

If you don't feel like coding this by hand, try out one of the many Configuration File parsers for python

Upvotes: 1

Related Questions