How To Write Ini-files Without Sections?
Solution 1:
[NB: the following is written for Python 3; you would need to make a couple of minor changes to make it run under Python 2.]
Maybe something like this; here, I write to an io.StringIO
object in memory, then take everything but the first line and write that out to the target file.
import configparser
import io
buf = io.StringIO()
ini_writer = configparser.ConfigParser()
ini_writer.set('DEFAULT', 'option1', '99')
ini_writer.set('DEFAULT', 'option2', '34')
ini_writer.set('DEFAULT', 'do_it', 'True')
ini_writer.write(buf)
buf.seek(0)
next(buf)
withopen('my.ini', 'w') as fd:
fd.write(buf.read())
By using the section name DEFAULT
we avoid having to create a new section first.
This results in:
$ cat my.ini
option1 = 99
option2 = 34
do_it = True
Solution 2:
As ConfigParser
doesn't support this I personally would probably opt to monkeypatch the write
method to support non-section writing.
from configparser import ConfigParser
def_write_section_custom(self, fp, section_name, section_items, delimiter):
for key, value in section_items:
value = self._interpolation.before_write(self, section_name, key, value)
if value isnotNoneornot self._allow_no_value:
value = delimiter + str(value).replace('\n', '\n\t')
else:
value = ''
fp.write('{}{}\n'.format(key, value))
fp.write('\n')
ini_writer = ConfigParser()
ConfigParser._write_section = _write_section_custom
ini_writer.add_section('SECTION')
ini_writer.set('SECTION', 'option1', '99')
ini_writer.set('SECTION', 'option2', '34')
ini_writer.set('SECTION', 'do_it', 'True')
withopen('my.ini', 'w') as f:
ini_writer.write(f)
With that I get:
$ cat my.ini
option1 = 99
option2 = 34
do_it = True
I've tested this under Python 3.8 so you would need to test/adjust for 2.7. Also bear in mind that the reading of the custom ini
would need to be adapted/monkeypatched. You could also wrap this into a custom ConfigParser
class of your own so that you have it reusable wherever you need it in your project.
Post a Comment for "How To Write Ini-files Without Sections?"