tags:

views:

178

answers:

1

configparser raises an exception if one parses a simple .properties (key/value) file which lacks section headers. Is there some workaround?

+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
would be great if there was an option in `configparser` to suppress that exception, for the sake of mere mortals like me :)
Tshepang