In a configuration file you have some options. These are grouped in name and value pairs. These pairs belong to one section and a section is indicated by a name in brackets.
The following Python class read such a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/python
import re
class WinIni:
"""
Read information from a text file formatted in WIN.INI format.
"""
def __init__(self, filename):
self.__hash = {}
sec = re.compile(r'^\[(.*)\]')
eq = re.compile(r'^([^=]+)=(.*)')
for line in open(filename, "r").readlines():
if sec.search(line):
lbracket, section, rbracket = sec.split(line)
section = section.strip() # remove leading and trailing spaces
elif eq.search(line):
left, item, value, right = eq.split(line)
self.__hash[section+'.'+item.strip()] = value.strip()
def __getitem__(self, aItem):
return self.__hash[aItem]
|
Assume you have the following configuration file:
; myconfig.ini ; Configuration data for my programme. ; [system] database = mysql
and somewhere in your Python programm you want to decide which database system you have to use:
conf = WinIni("myconfig.ini") db = conf["system.database"]
Now db contains "mysql".
Why not use ConfigParser? The ConfigParser module in the standard library already does this:
I agree. This functionality is already included with Python via the ConfigParser module.