Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

configparser without whitespace surrounding operator

Tags:

python

config

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?

like image 449
vlad Avatar asked Jan 22 '15 13:01

vlad


2 Answers

You can just use configparser (very recomended) but in simpler way, just add:

with open('example.ini', 'w') as configfile: ... config.write(configfile, space_around_delimiters=False)

As described in: https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write

 write(fileobject, space_around_delimiters=True)

Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.

like image 100
Pablo Daniel Estigarribia Davy Avatar answered Sep 19 '22 13:09

Pablo Daniel Estigarribia Davy


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
like image 40
rchang Avatar answered Sep 18 '22 13:09

rchang