Adding new section in config file without overwriting it using ConfigParser

13,903

Solution 1

Open the file in append mode instead of write mode. Use 'a' instead of 'w'.

Example:

config = configparser.RawConfigParser({'num threads': 1})
config.read('path/to/config')
try:
    NUM_THREADS = config.getint('queue section', 'num threads')
except configparser.NoSectionError:
    NUM_THREADS = 1
    config_update = configparser.RawConfigParser()
    config_update.add_section('queue section')
    config_update.set('queue section', 'num threads', NUM_THREADS)

    with open('path/to/config', 'ab') as f:
        config_update.write(f)

Solution 2

You just need to add one statement in between your code.

config.read('~/test/config.conf')

Example:

import configparser

config = configparser.ConfigParser()
config.read('config.conf')
config.add_section('Section2')
config.set('Section2', 'name', 'Mary')
config.set('Section2', 'number', '6')
with open('config.conf', 'w') as configfile:
    config.write(configfile)

When we are reading the config file in which we want to append, it initializes the config object with the data in our file. Then upon adding a new section, this data gets appended to the config...and then we are writing this data to the same file.

This can be one of the ways to append to the config file.

Share:
13,903

Related videos on Youtube

user2460869
Author by

user2460869

Updated on June 04, 2022

Comments

  • user2460869
    user2460869 almost 2 years

    I am writing a code in python. I have a confg file with following data:

    [section1]
    name=John
    number=3
    

    I am using ConfigParser module to add another section in this already existing confg file without overwriting it. But when I use below code:

    config = ConfigParser.ConfigParser()
    config.add_section('Section2')
    config.set('Section2', 'name', 'Mary')
    config.set('Section2', 'number', '6')
    with open('~/test/config.conf', 'w') as configfile:
        config.write(configfile) 
    

    it overwrites the file. I do not want to delete the previous data. Is there any way I can just add one more section? If I try to get and write the data of previous sections first, then it will become untidy as the number of sections will increase.