Import a file from a subdirectory?
Take a look at the Packages documentation (Section 6.4).
In short, you need to put a blank file named
__init__.py
in the lib
directory.
- Create a subdirectory named
lib
. - Create an empty file named
lib\__init__.py
. In
lib\BoxTime.py
, write a functionfoo()
like this:def foo(): print "foo!"
In your client code in the directory above
lib
, write:from lib import BoxTimeBoxTime.foo()
Run your client code. You will get:
foo!
Much later -- in linux, it would look like this:
% cd ~/tmp% mkdir lib% touch lib/__init__.py% cat > lib/BoxTime.py << EOFheredoc> def foo():heredoc> print "foo!"heredoc> EOF% tree liblib├── BoxTime.py└── __init__.py0 directories, 2 files% python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from lib import BoxTime>>> BoxTime.foo()foo!