在Python中使用configparser进行部分检查的问题

问题描述 投票:0回答:1

[我使用模块os和configparser在Python中编写了以下函数:

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

问题是,尽管config.ini中存在节和键,但该函数始终返回int(3)。如果我运行以下代码,一切都很好,并且值已更改:

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

此config.ini目前看起来像这样:

[PATHS]
data = /data

[API_KEYS]
marinetraffic_api = Test

我这样调用函数:

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

编辑:我尝试了以下操作,这更令人困惑:

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')

结果是:真正False

python-3.x configparser
1个回答
0
投票

找到了解决方案。但是,我不知道为什么第一次尝试没有解决:

© www.soinside.com 2019 - 2024. All rights reserved.