- 1 year ago
A case of import module from subdirectory - why does it work?
When importing a module from a subdirectory, it works because Python includes the subdirectories in the module search path. This allows you to organize your code into a directory structure while still being able to import and use modules from subdirectories.
By default, Python includes the current directory in the module search path. When you import a module, Python searches for the module in the current directory first, and if it doesn't find it there, it searches the other directories in the search path.
To import a module from a subdirectory, you need to ensure that the subdirectory containing the module is in the module search path. There are a few ways to accomplish this:
Add the subdirectory to the system path using
sys.path.append()
:pythonimport sys
sys.path.append('/path/to/subdirectory')
import module
This adds the specified directory to the system path temporarily for the current script.
Use a relative import if the module you want to import is in a package:
pythonfrom .subdirectory import module
This allows you to import a module relative to the current module's location within a package.
Use an absolute import with the full package path:
pythonfrom package.subdirectory import module
This allows you to import a module by specifying the full package path, including the subdirectory.
By using one of these methods, Python will be able to locate and import the module from the subdirectory successfully.