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 fil开发者_JAVA技巧e 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?
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
精彩评论