2

I have a config file that has multiple keys with the same name.

[parentnode]
    parentname = Name of parent
    child = Name of first child
    child = Name of second child
    child = Name of third child
    child = Name of fourth child

I need to be able to read this file, make modifications and write it to a different file. I was trying to see if I could read the config file and write it correctly without making any changes.

import configparser
from collections import OrderedDict

class MultiOrderedDict(OrderedDict):
    def __setitem__(self, key, value):
        if isinstance(value, list) and key in self:
            self[key].extend(value)
        else:
            super(MultiOrderedDict, self).__setitem__(key, value)


configParser = configparser.ConfigParser(defaults=None, dict_type=MultiOrderedDict, strict=False)
configParser.read('test.config')
with open('output.config', 'w') as configfile:
    configParser.write(configfile)

However, in the outputfile, I get the following, without the child keys. How do I ensure that my output file written using configparser.write() is the same as my input file?

[parentnode]
parentname = Name of parent
child = Name of first child
    Name of second child
    Name of third child
    Name of fourth child
softwarematter
  • 28,015
  • 64
  • 169
  • 263
  • 2
    Looks like you'll need to do something with https://github.com/python/cpython/blob/master/Lib/configparser.py#L905 and `.items()` and then `_write_section` to make it work with list values properly... (ie - looks like you need to create inherit the configparser and override that as well...) – Jon Clements Sep 09 '18 at 09:58
  • You may try to create an array from multiple values, like this: `child[] = first; child[] = second; child[] = third`, where **;** means a new line. As a bonus, working with array is easier than having multiple values with the same key. – Filip Happy Sep 09 '18 at 10:09
  • @JonClements thanks, I was able to override and resolve it. :) – softwarematter Sep 09 '18 at 10:44
  • @devnull great... I look forward to the self answer that's coming then? :p – Jon Clements Sep 09 '18 at 10:49

0 Answers0