python-3.xconfigparser

Problems with section check using configparser in Python


I wrote the following function in Python using the modules os and configparser:

def alter_config(section, key, value):
    if os.path.isfile('config.ini') is True:
        config = configparser.RawConfigParser()
        config.read('config.ini')
        if section in config is True:
            config.set(section, key, value)
            with open('config.ini', 'w') as configfile:
                config.write(configfile)
            return 1
        else:
            return 3
    else:
        return 2

Problem is, that the function always returns int(3) despite section and key exist in the config.ini. If I run the following code, everything is fine and the value is altered:

def alter_config(section, key, value):
    if os.path.isfile('config.ini') is True:
        config = configparser.RawConfigParser()
        config.read('config.ini')
        config.set(section, key, value)
        with open('config.ini', 'w') as configfile:
            config.write(configfile)
        return 1
    else:
        return 2

The config.ini looks like this at the moment:

[PATHS]
data = /data

[API_KEYS]
marinetraffic_api = Test

I call the function like this:

alter_config('API_KEYS', 'marinetraffic_api', 'test_value')

Edit: I tried the following and this is more confusing:

def test(section):
    if os.path.isfile('config.ini') is True:
        config = configparser.RawConfigParser()
        config.read('config.ini')
        print(section in config)
        if section in config is True:
            print(True)
        else:
            print(False)

test('API_KEYS')

Result is: True False


Solution

  • Found a solution. Nevertheless, I have no idea why the first attempt didn't work out:

    def alter_config(section, key, value):
        if os.path.isfile('config.ini') is True:
            config = configparser.RawConfigParser()
            config.read('config.ini')
            check_section = section in config
            if check_section is True:
                config.set(section, key, value)
                with open('config.ini', 'w') as configfile:
                    config.write(configfile)
                return 1
            else:
                return 3
        else:
            return 2