2

I am trying to access custom package modules, but getting "module not found" error. Under the directory `

└── C:\PythonProg
       ├── Test.py
       └── PackageTest
            ├── __init__.py
            ├── mod1.py
            └── mod2.py

In __init__.py, I have:

import mod1
import mod2

In mod1.py:

def mult(x,y):
    print(x*y)

In mod2.py:

def add(x,y):
    print(x,y)

In Test.py:

import PackageTest as pt
   
pt.mod1.add(2,3)
pt.mod2.mult(1,2)

When executing Test.py, why is the error popping up again, saying "No Module Named mod1"? I have tried many times, still facing same error.

Error :

Traceback (most recent call last):
File "c:\PythonProg\PackageTest\__init__.py", line 1, in <module>
 import mod1
ModuleNotFoundError: No module named 'mod1'
MatBBastos
  • 401
  • 4
  • 14

2 Answers2

3

Change your __init__.py to look like this:

from . import mod1
from . import mod2

And fix your test.py to look like this... (you had them swapped):

import PackageTest as pt

pt.mod1.mult(2,3)
pt.mod2.add(1,2)
Chris Sears
  • 6,502
  • 5
  • 32
  • 35
0

If the script you are wishing to import that is not in the current directory, you may want to take this approach:

make these changes in your test.py

import sys,os
sys.path.append(os.path.abspath(os.path.join('.', 'PackageTest')))
import mod1,mod2

mod2.add(2,3)
mod1.mult(1,2)