简体   繁体   中英

ConfigParser read Booleans / String / Integer at the same time with Python

Here is my 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.

A recursive function could be good for this:

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:

{'text': 'example text', 'size': 17, 'settings': None, 'run': False}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM