2

定义配置文件并使用 ConfigParser 定义一堆对象初始值(又名:构造函数值)来解析它的最佳方法是什么

例子:

[Person-Objects]
Name: X
Age: 12
Profession: Student
Address: 555 Tortoise Drive

Name: Y
Age: 29
Profession: Programmer
Address: The moon

然后能够在 Python 中解析它,这样我就可以得到类似的东西:

People = []
for person in config:
    People.append(person)
Person1 = People[0]
print Person1.Profession     # Prints Student
4

1 回答 1

2

您可以执行以下操作:

[person:X]
Age: 12
Profession: Student
Address: 555 Tortoise Drive

[person:Y]
Age: 29
Profession: Programmer
Address: The moon

然后在您的代码中:

config = ConfigParser()
config.read('people.ini')
people = []

for s in config.sections():
    if not s.startswith('person:'):
         continue

    name = s[7:]
    person = dict(config.items(s))
    person['name'] = name

    people.append(person)
于 2012-08-14T21:40:16.980 回答