Home > Net >  How do I import a module found in a sibling directory?
How do I import a module found in a sibling directory?

Time:01-14

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

CodePudding user response:

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.

  • Related