Importing a file (not a module).

Hendrik van Rooyen mail at microcorp.co.za
Mon Feb 9 02:40:07 EST 2009


"Luis Zarrabeitia" <ky..e at u...cu> wrote:

>Is there any way to "import" a .py file that is not on sys.path?
>I'd like to 'import' a file that resides somewhere on my filesystem without
>having to add it's directory to sys.path. At first, I thought that something
like
>
>my_module = __import__("path/to/file")
>
>would work, but I was mistaken. Ideally, the path would be specified as a
>relative path from the importer's module, and not from the CWD (that's another
>question, I guess).

I have used execfile(RelativeFromCWDOrAbsolutePathToTheFile) to do
this sort of thing. But beware - it does not create a module, so it's a bit
like:

from something import *

This may or may not be useful in your case.

- Hendrik





More information about the Python-list mailing list