How to eval a file

Alex Martelli aleax at aleax.it
Sun Feb 23 23:31:34 CET 2003


Donnal Walter wrote:
   ...
> I've been thinking about making a configuration file with a syntax
> something like this:
> 
> {
>    'log': './error.txt'
>    'splash': './welcome.png'
>    'icon': './prism.ico'
>    'login': 'C:/prism/user.dbm'
>    'cabinet': 'C:/prism/patient.dbm'
> }
> 
> Then I planned on reading the file something like this:
> 
>          f = open(filename)
>          txt = f.read().replace('\r\n','\n')

You presumably mean to insert commas at the end of the lines, right?

>          f.close()
>          self.__dict__.update(eval(txt))
> 
> Do I understand your previous reply to Björn to mean that I would still
> be better off using ConfigParser?

It's your call, of course; if you totally trust the text in the
file (e.g. nobody's going to use __import__ tricks there...),
then the main issue with your chosen format would seem to be
with the difficulty of editing its syntax.  Since you don't need
anywhere like the power of ConfigParser, while not keep it
simple on every plane, e.g:

file contains:

log     /error.txt
splash  /welcome.png
icon    ./prism.ico
login   C:/prism/user.dbm
cabinet C:/prism/patient.dbm

and you parse it with:

    lines = [ line.split() for line in open(filename) ]
    self.__dict__.update(dict(lines))

or something like that?


Alex





More information about the Python-list mailing list