Importing a file (not a module).

Luis Zarrabeitia kyrie at uh.cu
Sun Feb 8 23:01:46 EST 2009


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).

Related question: how could I change the sys.path for this_script.py without
changing it much? I'd like to have this_script a few more directories on its
pythonpath, but I don't want to clutter the begining of the script with
"sys.path.append(...)"s, specially because I need to do that for several
scripts. I thought of creating a modify_pythonpath.py and import it from all of
them, but I don't want to keep that script on the global python path nor on any
of the project folders (it is required by more than one). 

Currently I have a symlink from the original modify_pythonpath.py to each
project directory, but that seems clumsy.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie







More information about the Python-list mailing list