DEV Community

abbazs
abbazs

Posted on • Edited on

3 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay