Importing a file (not a module).

  • Thread starter Luis Zarrabeitia
  • Start date
L

Luis Zarrabeitia

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top