How to eval a file

Björn Lindberg d95-bli at
Sat Feb 22 17:42:59 CET 2003

I'm writing a program with a "configuration file" if you will, that
looks something like this:

collection = '''Abba %sdabba'''
topic = '''Gucko %s'''

I have trouble getting this information into Python. I was hoping I
could read this file as a string and then eval() it, to get the
variables collection & topic set to the respective strings in the
local context. Ie, in a class method:

    def read_file(name):
        f = open(name, 'r')
        string =
        self.collection = collection
        self.topic = topic


This gives the following error message:

    File "<string>", line 3
    collection = '''<h3%s</h3>'''
    SyntaxError: invalid syntax

So I tried using execfile(name) instead, but that doesn't work

The only thing I can come up with now is to import the file. This has
a number of drawbacks however: (i) I would have to modify the module
search path, (ii) The file would have to be named .py, (iii) It looks
ugly (at least to me) to have an import statement inside a function,
(iv) I am not even sure it would work as I expect.

Is there another way?


More information about the Python-list mailing list