Search code examples
pythonpython-3.xmodulenotfounderror

ModuleNotFoundError: No module named 'x' while importing modules


in Python 3 I try to import module (which imports another module) and I'm getting ModuleNotFoundError. My main module looks as follows:

from next_folder import adding
adding.add(1)

Then in the folder next folder I have two other modules. The first one is adding.py:

import substracting

def add(a):
    b = 1
    d = substracting.substract(20)
    c = a+b+d
    print(c)

The second one (in the same folder) is substracting.py:

def substract(c):
    d = c-1
    print(d)
    return d

While running main.py I'm getting the following error:

  File "C:\Users\LENOVO\PycharmProjects\pythonProject\main.py", line 1, in <module>
    from next_folder import adding
  File "C:\Users\LENOVO\PycharmProjects\pythonProject\next_folder\adding.py", line 1, in <module>
    import substracting
ModuleNotFoundError: No module named 'substracting'

Could you help me modify this code so the main.py actually works? Thanks!


Solution

  • You can use relative import in that case

    from . import substracting
    

    In python 3 relative imports are supported only in the form from . import submodule

    This would have worked as well:

    import next_folder.substracting as sub
    
    def add(a):
        b = 1
        d = sub.substract(20)
        c = a+b+d
        print(c)