include a file in a python program

Roy Smith roy at
Mon Sep 6 01:14:52 CEST 2010

In article <mailman.476.1283727475.29448.python-list at>,
 bussiere bussiere <bussiere at> wrote:

> i've got a python.txt that contain python and it must stay as it (python.txt)
> how can i include it in my program ?
> import python.txt doesn't work
> is there a way :
> a) to make an include("python.txt")
> b) tell him to treat .txt as .py file that i can make an import python ?
> i'am using python3

The simple solution (at least for unix-ish systems) would be to make a 
symlink -> python.txt.  If you don't have the ability to do 
that externally, you could even have your python program create the 
symlink on the fly, import the module, then delete the symlink.  The 
symlink could even be in /tmp.

Another possible solution is to read the entire file into a string and 
then eval() the string.  I'm assuming eval() still exists in python 3; 
does it?

Yet another possibility (never tried this, but it seems reasonable) 
would be to compile() your text file 

Of course, it would be a lot easier if you just renamed the file, but 
I'll take it as a given that there are external forces which prevent you 
from doing that.

More information about the Python-list mailing list