【问题标题】:Parsing multiple "key"="value" pairs in an INI section解析 INI 部分中的多个“key”=“value”对
【发布时间】:2019-02-20 02:02:40
【问题描述】:

我需要指针来使用 python 2.7 ConfigParser 解析 INI 文件,如下所示:

[google]
www.google.com domain_name=google location=external 

[yahoo]
www.yahoo.com domain_name=yahoo location=external

这是我试图做的:

Config = ConfigParser.ConfigParser()
try:
    Config.read("test.ini")
except Exception:
    pass

options = Config.options('google')
for option in options:
    print("Option is %s" % option)
    print("Value for %s is %s" % (option, Config.get('google', option)))

这就是输出:

Option is www.google.com domain_name
Value for www.google.com domain_name is google location=external

我希望能够将 www.google.com 和剩余的 key=value 对(domain_name=google; location=external) 解析为字典的每个部分的同一行。对此表示赞赏。

【问题讨论】:

  • 似乎问题在于 ConfigParser 对文件的可能结构有不同的假设。请问你的目标是什么?也许你可以直接使用 Ansible?

标签: python-2.7 ini configparser ansible-inventory


【解决方案1】:

我认为您要问的是一种遍历不同部分并将所有选项值添加到字典中的方法。

如果你没有卡在布局上,你可以做这样的事情

[google]
option=url=www.google.com,domain_name=google,location=external

[yahoo]
option=url=www.yahoo.com,domain_name=yahoo,location=external
import configparser

Config = configparser.ConfigParser()
try:
    Config.read("test.ini")
except Exception:
    pass

for section in Config.sections():
    for option in Config.options(section):
        values = Config.get(section, option)
        dict_values = dict(x.split('=') for x in values.split(','))

你也可以做一个字典的字典,但你的选项需要是唯一的。

dict_sections = {}
for section in Config.sections():
    for option in Config.options(section):
        values = Config.get(section, option)
        dict_values = dict(x.split('=') for x in values.split(','))
        dict_sections[option] = dict_values

另一个格式化选项:

[web_sites]
yahoo=url=www.yahoo.com,domain_name=yahoo,location=external
google=url=www.google.com,domain_name=google,location=external

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2022-10-21
    • 2015-07-08
    • 2013-02-17
    • 2015-05-20
    • 2017-06-06
    • 2016-04-10
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多