3

I am trying to import python module from one directory to another directory but not able to do it.

Here is my folder structure

Parent_Folder
---------Module1
         ----__init__.py (empty file)
         ----mymodule1.py
---------Module2
         ----__init__.py (empty file)
         ----mymodule2.py

I am trying to import

mymodule1.py

into

mymodule2.py

Here is the command that I have used to import the python module:

import Module1.mymodule1

but getting an error like

ModuleNotFoundError: No module named 'Module1'

I do see there are option like system-path at runtime, PYTHONPATH but I don't want to use those options.

Do you all have any other recommended solutions?

martineau
  • 119,623
  • 25
  • 170
  • 301
Rab
  • 159
  • 1
  • 11

2 Answers2

2

You can insert this at the top of module1.py, or in the init.py in Module1 if you're importing module1.py as well:

import sys
sys.path.append("../Module2") #assuming linuxOS 
import module2

This adds the Module2 directory to the system path and allows you to import files as if they were local to your current directory.

Other answers can be found in this link: beyond top level package error in relative import

jhso
  • 3,103
  • 1
  • 5
  • 13
  • Also, this seems to cover pretty much everything: https://stackoverflow.com/q/14132789/10475762 – jhso Jun 27 '21 at 23:26
-1

I'll give you an example of importing modules

I created the module1.py file

print("Module : 1")
def module01():#function
    print("module : 1.2")

class Module02:# class
        def module021(self):# function
            print('MODULE 1')

to import you need to indicate the file name

module2.py

from module1 import  module01 #import the function
from module1 import  Module02 #importing the class from module2.py




module01()
mod1 = Module02() #
mod1.module021()# imported class function
cardosource
  • 165
  • 1
  • 7