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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With