Search code examples
pythonconfigobj

How to update properties file using ConfigObj


Is their any way for updating value of a key in properties file using ConfigObj in python.

Before updating properties file:

hostKey = "value"

After updating properties file:

hostKey = "updatedValue"

Solution

  • From ConfigObj Documentation

    Creating a new config file is just as easy as reading one. You can specify a filename when you create the ConfigObj, or do it later [2].

    If you don’t set a filename, then the write method will return a list of lines instead of writing to file. See the write method for more details.

    Here we show creating an empty ConfigObj, setting a filename and some values, and then writing to file :

    from configobj import ConfigObj
    config = ConfigObj("test.config")
    config.filename ="test.config"
    config['keyword1'] = "value6"
    config['keyword2'] = "value2"
    config.write()
    

    I think similar way u can read and set to the same file name and then over-write the property you want.