I have a very simple ini file that I needs parsed. What is the best way I can
parse an ini file that doesn't include sections?
As in:
person=tall
height=small
shoes=big
Thats it. Can anyone help me?
The built-in ConfigParser module assumes at least one INI-style
section, which if it's not present, issues a
raise MissingSectionHeaderError
As such, if you don't have any headers, you may have to
hand-parse. However, that's not too bad:
from sys import stderr
options = {}
for i, line in enumerate(file("simple.ini")):
line = line.rstrip("\r\n").lstrip()
if not line or line.startswith(';') or line.startswith('#'):
continue # it's blank or a commented line
if '=' in line:
name, value = line.split('=', 1)
options[name.rstrip().lower()] = value.strip()
else:
stderr.write("Malformed option at line #%i\n" % (i+1))
person = options.get("person", "some default person value")
socks = options.get("socks", "some default sock value")
do_something(person, socks)
Adjust the strip() calls if you want to preserve odd white-spacing.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list