Parsing files

byrom r.byrom at rl.ac.uk
Tue Feb 10 09:29:53 EST 2004


> I believe ConfigParser (and INI-type files in general) expect all options to
> be grouped into sections.  If you don't need/want sections, why not just add

thats what I think too.

> a [general] section into which you put all your options?  Failing that, you
> could probably fudge things with something like this (untested):
> 
>     import tempfile
>     import ConfigParser
> 
>     def parse_config_file(f):
>         fd, fn = tempfile.mkstemp()
> 
>         # create a temporary config file with a dummy section
>         cfg = os.fdopen(fd)
>         cfg.write("[general]\n")
>         cfg.write(file(f).read())
>         cfg.close()
> 
>         # parse it
>         config = ConfigParser.ConfigParser()
>         config.read(fn)
> 
>         os.unlink(fn)
> 
>         return config
> 

This approach would definitely work. I managed to write quite a simple
parse routine myself:

    def __load(self, configfile):
        
        """ Initialises all variables (as read-in from configfile) """
	    
        configs = {}
        afile = file(configfile, 'rw')
        contents = afile.read().splitlines()
        for aline in contents:
           keyval = string.split(aline, '=')
           if len(keyval) > 1:
               configs[keyval[0]] = keyval[1]
        self.log.debug('properties read-in: %s ' % configs)
        return configs

And it returns a dictionary of all key-values pairs. Its not exactly
robust but it does the job :) 

anyway, thanks for your help!

Rob






More information about the Python-list mailing list