Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new section in config file without overwriting it using ConfigParser

Tags:

python

append

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.

like image 727
user2460869 Avatar asked Aug 06 '13 21:08

user2460869


1 Answers

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)
like image 197
virus.cmd Avatar answered Oct 17 '22 10:10

virus.cmd