How do I import a module(python file) that resides in the parent directory?
Both directories have a __init__.py
file in them but I still cannot import a file from the parent directory?
In this folder layout, Script B is attempting to import Script A:
Folder A: __init__.py Script A: Folder B: __init__.py Script B(attempting to import Script A)
The following code in Script B doesn't work:
import ../scriptA.py # I get a compile error saying the "." is invalid
Method 1: Import from parent directory using sys.Add the parent directory to the sys. path using the append() method. It is a built-in function of the sys module that can be used with a path variable to add a specific path for interpreters to search.
The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.
You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
toplevel_package/ ├── __init__.py ├── moduleA.py └── subpackage ├── __init__.py └── moduleB.py
In moduleB
:
from toplevel_package import moduleA
If you'd like to run moduleB.py
as a script then make sure that parent directory for toplevel_package
is in your sys.path
.
From the docs:
from .. import scriptA
You can do this in packages, but not in scripts you run directly. From the link above:
Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.
If you create a script that imports A.B.B, you won't receive the ValueError.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With