Quest
Quest

Reputation: 454

Python: How to add module from sibling folder

I have the following folder structure for my Python Project:

pythonApp             --> Folder
|--ABC                --> Package
   |--__init__.py     --> Empty File
   |--abctest.py      --> Module
|--DEF                --> Package
   |--__init__.py     --> Empty File
   |--deftest.py      --> Module
|--Common             --> Package
   |--__init__.py     --> Empty File
   |--constants.py    --> Module

I want to import constants.pyunder the Common package in the abctest.py. Using from Common import constants throws error Module not found. Is there any solution for this.

Upvotes: 2

Views: 881

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

in abctest.py, add the parent directory to python path using __file__ as current module name, then take the dirname of the dirname to compute it:

import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from Common import constants

note: python 2 seems to need a __init__.py file (even empty) in Common directory to be able to recognize Common as a module, whereas python 3 can do without.

Upvotes: 1

Related Questions