parsing .properties file in Python
Say you have, e.g.:
$ cat my.propsfirst: primosecond: secondothird: terzo
i.e. would be a .config
format except that it's missing a leading section name. Then, it easy to fake the section header:
import ConfigParserclass FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[asection]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline()
usage:
cp = ConfigParser.SafeConfigParser()cp.readfp(FakeSecHead(open('my.props')))print cp.items('asection')
output:
[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]
I thought MestreLion's "read_string" comment was nice and simple and deserved an example.
For Python 3.2+, you can implement the "dummy section" idea like this:
with open(CONFIG_PATH, 'r') as f: config_string = '[dummy_section]\n' + f.read()config = configparser.ConfigParser()config.read_string(config_string)
My solution is to use StringIO
and prepend a simple dummy header:
import StringIOimport osconfig = StringIO.StringIO()config.write('[dummysection]\n')config.write(open('myrealconfig.ini').read())config.seek(0, os.SEEK_SET)import ConfigParsercp = ConfigParser.ConfigParser()cp.readfp(config)somevalue = cp.getint('dummysection', 'somevalue')