开发者

Reading object tree from file into Python

开发者 https://www.devze.com 2022-12-22 22:36 出处:网络
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 cre

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

0

精彩评论

暂无评论...
验证码 换一张
取 消