3

I need to modify a config file using python. The file has a format similar to

property_one = 0
property_two = 5

i.e there aren't any section names.

Python's configparser module doesn't support sectionless files, but I can use it to load them easily anyway using the trick from here: https://stackoverflow.com/a/26859985/11637934

parser = ConfigParser()
with open("foo.conf") as lines:
    lines = chain(("[top]",), lines)  # This line does the trick.
    parser.read_file(lines)

The problem is, I can't find a clean way to write the parser back to a file without the section header. The best solution I have at the moment is to write the parser to a StringIO buffer, skip the first line and then write it to a file:

with open('foo.conf', 'w') as config_file, io.StringIO() as buffer:
    parser.write(buffer)
    buffer.seek(0)
    buffer.readline()
    shutil.copyfileobj(buffer, config_file)

It works but it's a little ugly and involves creating a second copy of the file in memory. Is there a better or more concise way of achieving this?

sophros
  • 14,672
  • 11
  • 46
  • 75
moly
  • 321
  • 3
  • 14
  • 1
    Why is https://stackoverflow.com/a/2885753/6573902 insufficient? – sophros Jun 12 '19 at 16:36
  • 1
    @sophros that answer allows you to read a sectionless file, but when you write it back to a file it will include the dummy section header. I need it not to. – moly Jun 12 '19 at 16:51
  • Why not just `config_file.write(buffer.read())` (as last line in the `with` block)? – Tomerikoo Feb 10 '21 at 14:02
  • Does this answer your question? [How to write ini-files without sections?](https://stackoverflow.com/questions/66137056/how-to-write-ini-files-without-sections) – Tomerikoo Feb 10 '21 at 14:03

1 Answers1

3

Stumbled on a less ugly way of doing this:

text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
    config_file.write(text)
moly
  • 321
  • 3
  • 14