1a1a11a
1a1a11a

Reputation: 1277

how to import module in upper directory in python

I have several python modules in the project and I put them in different folders, for example,

pythonProject\folderA\modulex.py
pythonProject\folderB\moduley.py
pythonProject\commonModule\module1.py 

I have __init__.py in each folder. In this situation, how can I import module1 into modulex?

Upvotes: 1

Views: 5291

Answers (3)

mmachine
mmachine

Reputation: 926

The best if all modules are in the same directory. In case any of them in different possible use of os.chdir(path). With os.chdir(path) method (https://docs.python.org/3.2/library/os.html) possible change working directory in your program.

import os
import modulex

#assume working directory is "pythonProject\folderA\"

os.chdir(r'pythonProject\commonModule\')
#now working directory is "pythonProject\commonModule\"

import module1

Upvotes: 0

LittleQ
LittleQ

Reputation: 1925

Use relatively import

# in modulex
from ..commonModule import module1

Upvotes: 3

Bharadwaj
Bharadwaj

Reputation: 745

Whenever you have python packages (those folders that contain __init__.py files), you can import the modules like below

modulex.py
----------

from pythonproject.commonModule import module1

Try this, If the pythonproject is not defined by the tool, then you could use the relative addressing like below

from ..commonModule import module1

Upvotes: 1

Related Questions