user2460869
user2460869

Reputation: 471

Adding new section in config file without overwriting it using ConfigParser

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.

Upvotes: 16

Views: 21056

Answers (2)

Ronak Jain
Ronak Jain

Reputation: 81

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.

Upvotes: 8

virus.cmd
virus.cmd

Reputation: 344

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)

Upvotes: 9

Related Questions