首页 > 解决方案 > Python configparser 自动转换为布尔值

问题描述

我正在编写一个类来解析各种配置文件。它包含yaml文件和ini+cfg文件的方法。

解析 yamls 工作正常,但我对另外两个有问题。基本上我阅读它们,我解析它们,但是如果我的config.cfg文件看起来像这样:

[foo]
bar: True

的值为config['foo']['bar']will 'True', not True,所以我最终得到一个字符串。

我不想强迫我班级的用户转换给定的值。有没有办法解决这个问题,所以字符串变成布尔值?

PS阅读配置后,我转换返回读取值的字典,如下所示:

config_parser = configparser.ConfigParser()
config_parser.read(config_file_path)
return {section: dict(config_parser.items(section)) for section in config_parser.sections()}

标签: python-3.xconfigparser

解决方案


推荐阅读