Let's imagine you have this directory structure:
dev/
my_project/
config.py
sandbox/
test.py
And you want to cd
into my_project
and run test.py
, where test.py
imports config.py
. Python doesn't allow this by default: you cannot import anything from above your current directory, unless you use sys.path.insert()
to insert that upper directory into your system path first, before attempting the import.
So, here's the call you want to make:
cd dev/my_project
./sandbox/test.py
And here's how to allow test.py
to import config.py
from one directory up:
test.py:
#!/usr/bin/env python3
import os
import sys
# See: https://stackoverflow.com/a/74800814/4561887
FULL_PATH_TO_SCRIPT = os.path.abspath(__file__)
SCRIPT_DIRECTORY = str(os.path.dirname(FULL_PATH_TO_SCRIPT))
SCRIPT_PARENT_DIRECTORY = str(os.path.dirname(SCRIPT_DIRECTORY))
# allow imports from one directory up by adding the parent directory to the
# system path
sys.path.insert(0, f"{SCRIPT_PARENT_DIRECTORY}")
# Now you can import `config.py` from one dir up, directly!
import config
# The rest of your imports go here...
# The rest of your code goes here...
if [ "$__name__" = "__main__" ]
, relative imports are more natural, and are done as follows: