我需要使用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,剩下的键= value对(domain_name = google; location; location = external)在同一行中,将每个部分放入字典中。任何赞赏的指针。
我认为您要问的是循环浏览不同部分并将所有选项值添加到字典中的方法。
如果您不卡在布局上,您可以做这样的事情
[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
希望这会有所帮助!