To import a module from a parent directory in Python, you can use the sys.path.append
function to add the directory to the Python path, and then use the import
statement to import the module.
For example, suppose you have the following directory structure:
Code language: plaintext (plaintext)project/ __init__.py calc.py child/ __init__.py script.py
And you want to import the calc
module from the project
directory in the project/child/script.py
file.
You can do this by adding the parent directory, using ../
, to the Python path and then importing the project.calc
module:
import sys
sys.path.append("../")
import project.calc
Code language: Python (python)
Alternatively, you can use the PYTHONPATH
environment variable to specify directories that should be added to the Python path. For example:
export PYTHONPATH="/path/to/project:$PYTHONPATH"
Code language: Bash (bash)
Then you can import the calc
module in the script.py
file as follows:
import project.calc
Code language: Python (python)
Note on Relative Imports
The answer above assumes you are calling the script directly like this:
python3 child/script.py
Instead, if your Python script is part of a package and you are wanting to use a module in a parent folder then you can simply use a relative import like this:
import ..calc
Code language: JavaScript (javascript)
However, if you do this without using packages then you will receive this error:
ImportError: attempted relative import with no known parent package
Code language: JavaScript (javascript)
If you want to package your code so that you can use relative imports and avoid modifying the path then you can follow the Packaging Python Projects guide.
References
- Python documentation on
sys.path
: https://docs.python.org/3/library/sys.html#sys.path - Python documentation on the
import
statement: https://docs.python.org/3/reference/simple_stmts.html#import - Python documentation on relative imports: https://docs.python.org/3/tutorial/modules.html#intra-package-references
- Packaging Python Projects guide: https://packaging.python.org/tutorials/packaging-projects/
Leave a Reply