A quick web search shows many people are trying to edit sectionless configuration files with Python:
and it seems the common workaround is to add a dummy top-level section to be able to read the file using read_string(), which does not seem like a good solution.
Wouldn’t it make sense to add a ConfigParser
__init__() option to allow reading a writing such files?
(Explain why this feature or enhancement should be implemented and how it would be used.
Add examples, if applicable.)
If user would initialize configparser with let’s say ‘allow_no_sections’ option, like
cp = ConfigParser(allow_no_sections=True), instead of raising
MissingSectionHeaderError, ConfigParser would understand that the content is simple key = value type (one default section) and parse it accordingly.
How else would you edit sectionless config files with only built-in libs? Custom parsers?
If you know that the section is never present you could
- read in the file
- add a header
- save as string
- remove header
- save file
I’ve done this exact thing, but then I realized the file format is so simple that
str.partition("=") with some
str.strip() calls was good enough.
I also don’t think there’s anything wrong with something on PyPI handling this situation.
One comment said that the file in question was in .ini format (ie, had sections) and therefore could be parsed with configparser. The more important issue is that configparser removes comment lines while apparently people comment and uncomment key-value lines rather than changing the value to and from the default value. A more important issue might be to add comment preservation.
This is about a file with a section header; as the title says, it is about changing and writing it out.
This is about editing a file with code to replace certain lines with other lines. The solution was about using regexes to find the lines to be replaced. It was not really about using configparser.
This seems like a somewhat plausible request. The main problem is that configparser returns a dict of string dicts, one for each section, whereas with no sections, one really wants one dict of strings. However, a Configparser
__init__ option cannot turn a Configparser object (dict of dicts) into a dict of strings, and if it did, the methods depending on being a dict of dicts would not work.
A better proposal would be to add a SimpleConfigparser class that is essentially a section dict. The justification would be the possibility to reuse the configparser section dict creation machinery that is somewhat flexible about key-value format and which recognizes continuation lines by indent (and can do interpolation, which I have never used). I would be tempted to leave off the legacy interface for value access and just use the mapping access added in 3.2.