0

I want to read a configuration file in INI format that has comment lines. I don't want to lose those lines when the application writes the configuration back to the file.

How can I do this?

Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> cfg = configparser.ConfigParser()
>>> cfg.read_string('''[DEFAULT]
... # comment
... parameter = 7''')
>>> f = open('my.conf', 'w')
>>> cfg.write(f)
>>> f.close()
>>> 
$ cat my.conf
[DEFAULT]
parameter = 7
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • Tags are a perfectly good way to for someone to find your post. The language in the title will not help it be found. The Python 3 tag will tell the answerer what the language is. – Stephen Rauch Mar 25 '18 at 21:44
  • Possible duplicate of [Adding comment with configparser](https://stackoverflow.com/questions/8533797/adding-comment-with-configparser) – Stop harming Monica Mar 25 '18 at 22:24
  • 1
    I flagged the question as a duplicate but then I realized it is probably not. Maybe you can try something along the lines in the accepted answer but overriding also the `read` method so the comments in the input file are stored in the `ConfigParser` object. TBH I think I would write my own parser instead. – Stop harming Monica Mar 25 '18 at 22:33
  • @Goyo: I also often think about I need to write something myself. But I was wondering that a Python-offical lib is not able to handle such a simple task. – buhtz Mar 26 '18 at 12:06
  • Unless I missed something the only built-in support for comments consists in discarding them when reading files. – Stop harming Monica Mar 26 '18 at 12:24

1 Answers1

0

The ConfigObj is the solution.

buhtz
  • 10,774
  • 18
  • 76
  • 149