How do I import a module found in a sibling directory?

Question:

Suppose I have the following file structure below. From the root, I want to run A.py which will import functions in B.py. How do I load a module found in a sibling directory?

root :
 |
 |__SiblingA:
 |    __A.py
 |     
 |__SiblingB:
 |      __B.py
Asked By: Dan Lee

||

Answers:

To answer your question, lets say you want to import a function named as create from SiblingB/B.py

To import the create function from a file named B.py located inside a sibling directory named SiblingB one directory above the current file, you can use the following code:

from ..SiblingB.B import create

This uses the from .. syntax to move one directory above the current location, then specifies the path to the SiblingB directory, and finally imports the create function from the B.py file inside that directory.

Please note that this code assumes that the SiblingB directory is a valid package with a proper __init__.py file, and that the B.py file is located within that package.

Answered By: ANFAS PV
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.