Good day! There is a code like:

from configobj import ConfigObj spec = """ example = boolean(default=True) [section1] value1 = [value1] value2 = integer(default=15) """ from StringIO import StringIO config = ConfigObj(configspec=StringIO(spec)) from validate import Validator config.validate(Validator(), copy=True) config.filename = 'test.conf.sample' config.write() 

Actually the question is: how to substitute your variables when generating a config so that it is something like this:

  example = boolean(default=True) TEST value1 = test value2 = integer(default=15) 

Tried to do so

 config['section1'] = 'TEST' config['value1'] = "test" 

But nothing works, what could be the problem? Thanks in advance for your help!

  • Try to make config.write() after changing parameters. - Daniyar Supiev
  • where is it? config.write () after spec = "" "example = boolean (default = True) [section1] value1 = [value1] value2 = integer (default = 15)" "" - Rumato
  • I just did not understand the comment. - Rumato

1 answer 1

To change sections / keys, you can use the walk function, to which the function called for each section / key is transferred, but in this function you can define the change logic:

 def transform(section, key): val = section[key] newkey = key.replace('section1', 'TEST') section.rename(key, newkey) if isinstance(val, (tuple, list, dict)): pass else: try: val = val.replace('section1', 'TEST') section[newkey] = val except: pass from configobj import ConfigObj spec = """\ example = boolean(default=True) [section1] value1 = [value1] value2 = integer(default=15) """ try: from StringIO import StringIO except ImportError: from io import StringIO config = ConfigObj(configspec=StringIO(spec)) from validate import Validator config.validate(Validator(), copy=True) config.filename = 'test.conf.sample' config['section1']['value1'] = "test yeah!" config.walk(transform, call_on_sections=True) config.write() print(open(config.filename).read()) 

Console:

 example = True [TEST] value2 = 15 value1 = test yeah!