configparser
raises an exception if one parses a simple .properties (key/value) file which lacks section headers. Is there some workaround?
views:
178answers:
1
+5
A:
Say you have, e.g.:
$ cat my.props
first: primo
second: secondo
third: 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:
>>> class 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()
...
>>> cp.readfp(FakeSecHead(open('my.props')))
>>> cp.items('asection')
[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]
where cp
is typically an instance of ConfigParser.SafeConfigParser
.
Alex Martelli
2010-05-12 14:36:38
would be great if there was an option in `configparser` to suppress that exception, for the sake of mere mortals like me :)
Tshepang
2010-05-12 14:52:59