Welcome, guest | Sign In | My Account | Store | Cart

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, 22 lines
 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".

2 comments

andy mckay 21 years, 9 months ago  # | flag

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')
Joel Lawhead 21 years, 9 months ago  # | flag

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

Created by Farhad Fouladi on Mon, 10 Jun 2002 (PSF)
Python recipes (4591)
Farhad Fouladi's recipes (2)

Required Modules

Other Information and Tasks