How can I import a py script by its absolute path name?

Terry Hancock hancock at anansispaceworks.com
Thu Jul 14 14:02:06 EDT 2005


On Thursday 14 July 2005 07:43 am, Thorsten Kampe wrote:
> * Edvard Majakari (2005-07-14 12:52 +0100)
> > could ildg <could.net at gmail.com> writes:
> >> I want to import c:\xxx\yyy\zzz.py into my programme,
> >> What should I do?
> >> Thank you~
> > 
> > import sys
> > sys.path.append('c:\xxx\yyy')
> 
> "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')"

While this will work, I think the OP may want something simpler:

my_mod = __import__('c:\\xxx\\yyy\\mymodule.py')

especially if this is following up on the relative path workaround (in
which case the result will be buried in the relative path import function).

The sys.path solution is the technique you should be using to
establish a top-level directory for your package.  Once you do
that, you can use __init__.py and dotted imports to get to everything
in your package by "absolute" paths (that is, relative to the top-level
package, rather than to each sub-package).  This is the preferred
Python approach in the current design.

However, the idea that it would be desireable to import packages by
something like "../main_package/other_subpackage/module2.py"
has been suggested, and you can implement something like this using
the __import__ built-in as suggested above.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com





More information about the Python-list mailing list