import from a file in a subdirectory

Mark McEahern marklists at mceahern.com
Tue Apr 30 15:37:59 EDT 2002


[rdack]
> 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?

Short answer:  Look into something called "packages".

Demo:

  parent/
    a.py
    /subdir/
      __init__.py
      b.py

# a.py
from subdir import b
b.foo()

# __init__.py
# The mere presence of this file makes the dir a package.
pass

# b.py
def foo():
  print "lo and behold"

// mark





More information about the Python-list mailing list