[英]ConfigParser read Booleans / String / Integer at the same time with Python
Here is my config.ini :这是我的config.ini :
[LOADER]
text = example text
size = 17
settings = None
run = False
But when I print it, using:但是当我打印它时,使用:
config = ConfigParser()
config.read('config.ini')
print(config._sections['LOADER'])
I get this:我明白了:
{'text': 'example text', 'size': '17', 'settings': 'None', 'run': 'False'}
But I want this:但我想要这个:
{'text': 'example text', 'size': 17, 'settings': None, 'run': False}
I tried several methods with ConfigParser, I tried to edit the list to replace the strings in boolean, but I really can't do it, thanks.我用ConfigParser尝试了几种方法,我试图编辑列表以替换boolean中的字符串,但我真的做不到,谢谢。
A recursive function could be good for this:递归 function 可能对此有好处:
def load_it(obj):
if isinstance(obj, dict):
return {k: load_it(v) for k, v in obj.items()}
if isinstance(obj, list):
return [load_it(elem) for elem in obj]
if isinstance(obj, str):
if obj == 'None':
return None
if obj.isnumeric():
return int(obj)
if obj.replace('.', '', 1).isnumeric():
return float(obj)
if obj.upper() in ('TRUE', 'FALSE', 'T', 'F'):
return obj.upper() in ('TRUE', 'T')
return obj
data = load_it({'text': 'example text', 'size': '17', 'settings': 'None', 'run': 'False'})
print(data)
Output: Output:
{'text': 'example text', 'size': 17, 'settings': None, 'run': False}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.