Importing external modules is a common practice in Python development. However, when the module resides in a subdirectory, importing it requires a specific approach.
Problem Statement
Suppose you have a file named tester.py located in the /project directory. This directory contains a subdirectory called lib, which houses a file named BoxTime.py. Your goal is to import BoxTime into tester.py.
Initial Attempt and Error
You attempted to import BoxTime using the following code:
import lib.BoxTime
However, this resulted in an ImportError, as Python could not find the module named lib.BoxTime.
Solution: Implementing a Package
To resolve this issue, you need to convert the lib directory into a Python package. This involves creating an empty file named __init__.py inside the lib directory.
/project /tester.py /lib/__init__.py /lib/BoxTime.py
This __init__.py file acts as a package initializer, informing Python that the directory is a package containing Python modules.
Importing the Module Correctly
Once the __init__.py file is in place, you can import BoxTime using either of the following methods:
import lib.BoxTime
or
import lib.BoxTime as BT BT.bt_function()
The second method assigns BoxTime to the variable BT, allowing you to access its functions using the shorter alias.
The above is the detailed content of How to Import Modules from Subdirectories in Python?. For more information, please follow other related articles on the PHP Chinese website!