ActiveState Code

Recipe 132326: Read configuration from a text file in WinIni format!


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.

Python
 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]

Discussion

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".

Comments

  1. 1. At 7:18 p.m. on 11 jun 2002, andy mckay said:

    Why not use ConfigParser? The ConfigParser module in the standard library already does this:

    import ConfigParser
    
    cfg = ConfigParser.ConfigParser()
    cfg.readfp(open('myconfig.ini'))
    print cfg.get('system', 'database')
    
  2. 2. At 8:54 p.m. on 14 jun 2002, Joel Lawhead said:

    I agree. This functionality is already included with Python via the ConfigParser module.

Sign in to comment