DEV Community

abbazs
abbazs

Posted on • Edited on

How to add folders to python modules search path?

Consider you have development folder structure like this:

.
├── app
│   └── piccolo_conf.py
├── poetry.lock
├── pyproject.toml
├── README.md
└── work
Enter fullscreen mode Exit fullscreen mode

In this folder structure, app is the main application development folder. You want it to be clean. And you also want to write some experiment codes and test them to ensure that the code is meeting the requirement. While doing so, often it is required to refer to the code inside the app folder.

How to refer to the code inside the app folder while having the experiment code in the work folder?

Following code address that:

import sys
from pathlib import Path
# Path.cwd() - Get the current working directory
# Path(Path.cwd()).parent - Get the current working directory parent
# glob("app/**") - Get all the folders inside the app folder 
p = list(Path(Path.cwd()).parent.glob("app/**"))
sys.path.append(str(p[0].parent.absolute()))
for x in p:
    pth = str(x.absolute())
    # Exclude the folders that starts with __
    if not x.name.startswith("__"):
        sys.path.append(pth)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)