[Python] Update INI file without removing comments

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following INI file:

    [TestSettings]
    # First comment goes here
    environment = test

    [Browser]
    # Second comment goes here
    browser = chrome
    chromedriver = default

    ...


    I'm using Python 2.7 to update the ini file:

    config = ConfigParser.ConfigParser()
    config.read(path_to_ini)
    config.set('TestSettings','environment',r'some_other_value')

    with open(path_to_ini, 'wb') as configfile:
    config.write(configfile)


    How can I update the INI file without removing the comments. The INI file is updated but the comments are removed.

    [TestSettings]
    environment = some_other_value

    [Browser]
    browser = chrome
    chromedriver = default

    Continue reading...

Compartilhe esta Página