import from a file in a subdirectory

Pearu Peterson pearu at cens.ioc.ee
Tue Apr 30 16:00:09 EDT 2002


On 30 Apr 2002, holger krekel wrote:

> On Tue, Apr 30, 2002 at 12:27:03PM -0700, rdack wrote:
> > i have a script running in a directory.
> > i want to call a subroutine in a file in a subdirectory.
> > 
> > in the first file i said  from subdir/ff.py import  subrtn
> > python doesn't like the slash.
> > 
> > how do i do it?
> 
> import sys
> sys.path.append('subdir')
> 
> import ff

I would suggest 

  sys.path.insert(0,'subdir')
  import ff
  del sys.path[0]

in case there also exists ff module/package in Python tree.

And note that if there is a ff Python module/package and it is imported
before, say, by other modules, then the above hooks are useless as

  import ff

uses already imported module, not the one in 'subdir'. I am not sure but
may be reload(ff) will fix this:

  sys.path.insert(0,'subdir')
  import ff
  reload(ff)
  del sys.path[0]


Regards,
	Pearu






More information about the Python-list mailing list