0

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?

bismo
  • 1,257
  • 1
  • 16
  • 36
  • A good solution would be to add `model_folder` to your $PYTHONPATH environment variable. Then you can import any of its subdirectories without worry. – John Gordon Nov 22 '22 at 23:02

1 Answers1

0

sys.path[0] contain your root directory (the directory where the program is located). You can use that to add your sub-directories.

import sys
sys.path.append( sys.path[0] + "/model_modules")
import foo

and for cases where foo.py may exist elsewhere:

import sys
sys.path.insert( 1, sys.path[0] + "/model_modules") # put near front of list
import foo
user3435121
  • 633
  • 4
  • 13