python - 在 ConfigParser 中定义对象值列表

标签 python config

定义配置文件并使用 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

最佳答案

你可以这样做:

[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)

关于python - 在 ConfigParser 中定义对象值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960585/

相关文章:

c# - 在 app.config 的 configSection 中避免版本特定信息

Python 使用配置文件记录到不同的目的地

json - Keycloak:是否可以在配置 json 文件中编写脚本组?

python - 地理 Pandas 不会爆炸

Python排序列表和关联列表

python - 提取 URL 的特定部分

c++ - 如何将 dramsim2 库接口(interface)与 PINtool 链接

python - 使用 pycurl 从服务器获取响应

python - 了解 ndb 键类与 KeyProperty

config - 在多个项目中加载 Elixir 配置层次结构