Let's say I have the following directory
model_folder | | ------- model_modules | | | ---- __init__.py | | | ---- foo.py | | | ---- bar.py | | ------- research | | | ----- training.ipynb | | | ----- eda.ipynb | | ------- main.py and I want to import model_modules into a script in research
I can do that with the following
import sys sys.path.append('/absolute/path/model_folder') from model_modules.foo import Foo from model_modules.bar import Bar However, let's say I don't explicitly know the absolute path of the root, or perhaps just don't want to hardcode it as it may change locations. How could I get the absolute path of module_folder from anywhere in the directory so I could do something like this?
import sys sys.path.append(root) from model_modules.foo import Foo from model_modules.bar import Bar I referred to this question in which one of the answers recommends adding the following to the root directory, like so:
utils.py from pathlib import Path def get_project_root() -> Path: return Path(__file__).parent.parent model_folder | | ------- model_modules | | | ---- __init__.py | | | ---- foo.py | | | ---- bar.py | | | ------- src | | | ---- utils.py | | | | | ------- research | | | ----- training.ipynb | | | ----- eda.ipynb | | ------- main.py But then when I try to import this into a script in a subdirectory, like training.ipynb, I get an error
from src.utils import get_project_root root = get_project_root ModuleNotFoundError: No module named 'src' So my question is, how can I get the absolute path to the root directory from anywhere within the directory in python?
model_folderto your $PYTHONPATH environment variable. Then you can import any of its subdirectories without worry.