Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a file from a subdirectory?

I have a file called tester.py, located on /project.

/project has a subdirectory called lib, with a file called BoxTime.py:

/project/tester.py /project/lib/BoxTime.py 

I want to import BoxTime from tester. I have tried this:

import lib.BoxTime 

Which resulted:

Traceback (most recent call last):   File "./tester.py", line 3, in <module>     import lib.BoxTime ImportError: No module named lib.BoxTime 

Any ideas how to import BoxTime from the subdirectory?

EDIT

The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:

import lib.BoxTime as BT ... BT.bt_function() 
like image 764
Adam Matan Avatar asked Aug 11 '09 14:08

Adam Matan


People also ask

Does Python search subdirectories for import?

The PYTHONPATH is the environment variable that contains the path of the directories that Python searches to import the packages. Therefore, if we add the subdirectory to the PYTHONPATH , Python will first look at the directories in PYTHONPATH and import it from there.

Is a subdirectory a folder?

A subdirectory is a type of website hierarchy under a root domain that uses folders to organize content on a website. A subdirectory is the same as a subfolder and the names can be used interchangeably.

What is the difference between a directory and a subdirectory?

Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a subdirectory.


2 Answers

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.

like image 83
4 revs, 3 users 69% Avatar answered Oct 14 '22 00:10

4 revs, 3 users 69%


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

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

    from lib import BoxTime BoxTime.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 << EOF heredoc> def foo(): heredoc>     print "foo!" heredoc> EOF % tree lib lib ├── BoxTime.py └── __init__.py  0 directories, 2 files % python  Python 2.7.6 (default, Mar 22 2014, 22:59:56)  [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from lib import BoxTime >>> BoxTime.foo() foo! 
like image 38
hughdbrown Avatar answered Oct 14 '22 00:10

hughdbrown