Import a file from a subdirectory? Import a file from a subdirectory? python python

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

in the lib directory.

  • Create a subdirectory named lib.
  • Create an empty file named lib\
  • In lib\, write a function foo() like this:

    def foo():    print "foo!"
  • In your client code in the directory above lib, write:

    from lib import
  • Run your client code. You will get:


Much later -- in linux, it would look like this:

% cd ~/tmp% mkdir lib% touch lib/ cat > lib/ << EOFheredoc> def foo():heredoc>     print "foo!"heredoc> EOF% tree liblib├──└── __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>>>!

You can try inserting it in sys.path:

sys.path.insert(0, './lib')import BoxTime