Using ConfigParser to read a file without section name
Alex Martelli provided a solution for using ConfigParser
to parse .properties
files (which are apparently section-less config files).
His solution is a file-like wrapper that will automagically insert a dummy section heading to satisfy ConfigParser
's requirements.
Enlightened by this answer by jterrace, I come up with this solution:
- Read entire file into a string
- Prefix with a default section name
- Use StringIO to mimic a file-like object
ini_str = '[root]\n' + open(ini_path, 'r').read()ini_fp = StringIO.StringIO(ini_str)config = ConfigParser.RawConfigParser()config.readfp(ini_fp)
EDIT for future googlers: As of Python 3.4+ readfp
is deprecated, and StringIO
is not needed anymore. Instead we can use read_string
directly:
with open('config_file') as f: file_content = '[dummy_section]\n' + f.read()config_parser = ConfigParser.RawConfigParser()config_parser.read_string(file_content)
You can do this in a single line of code.
In python 3, prepend a fake section header to your config file data, and pass it to read_string()
.
from configparser import ConfigParserparser = ConfigParser()with open("foo.conf") as stream: parser.read_string("[top]\n" + stream.read()) # This line does the trick.
You could also use itertools.chain()
to simulate a section header for read_file()
. This might be more memory-efficient than the above approach, which might be helpful if you have large config files in a constrained runtime environment.
from configparser import ConfigParserfrom itertools import chainparser = ConfigParser()with open("foo.conf") as lines: lines = chain(("[top]",), lines) # This line does the trick. parser.read_file(lines)
In python 2, prepend a fake section header to your config file data, wrap the result in a StringIO
object, and pass it to readfp()
.
from ConfigParser import ConfigParserfrom StringIO import StringIOparser = ConfigParser()with open("foo.conf") as stream: stream = StringIO("[top]\n" + stream.read()) # This line does the trick. parser.readfp(stream)
With any of these approaches, your config settings will be available in parser.items('top')
.
You could use StringIO in python 3 as well, perhaps for compatibility with both old and new python interpreters, but note that it now lives in the io
package and readfp()
is now deprecated.
Alternatively, you might consider using a TOML parser instead of ConfigParser.