pythonconfig

configparser without whitespace surrounding operator


This script:

import ConfigParser

config = ConfigParser.ConfigParser()
config.optionxform = str
with open('config.ini', 'w') as config_file:
    config.add_section('config')
    config.set('config', 'NumberOfEntries', 10)
    config.write(config_file)

produces:

[config]
NumberOfEntries = 10

where key and property are not delimited by "=" but with " = " (equal sign surrounded by spaces).

How to instruct Python, to use "=" as delimiter with ConfigParser?


Solution

  • You could extend the ConfigParser class and override the write method such that it behaves the way you would like.

    import ConfigParser
    
    class GrumpyConfigParser(ConfigParser.ConfigParser):
      """Virtually identical to the original method, but delimit keys and values with '=' instead of ' = '"""
      def write(self, fp):
        if self._defaults:
          fp.write("[%s]\n" % DEFAULTSECT)
          for (key, value) in self._defaults.items():
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
          fp.write("\n")
        for section in self._sections:
          fp.write("[%s]\n" % section)
          for (key, value) in self._sections[section].items():
            if key == "__name__":
              continue
            if (value is not None) or (self._optcre == self.OPTCRE):
    
              # This is the important departure from ConfigParser for what you are looking for
              key = "=".join((key, str(value).replace('\n', '\n\t')))
    
            fp.write("%s\n" % (key))
          fp.write("\n")
    
    if __name__ == '__main__':
      config = GrumpyConfigParser()
      config.optionxform = str
      with open('config.ini', 'w') as config_file:
        config.add_section('config')
        config.set('config', 'NumberOfEntries', 10)
        config.write(config_file)
    

    This produces the following output file:

    [config]
    NumberOfEntries=10