Python: ModuleNotFoundError: No module named 'xyz'

Question:

I have a folder, called ABC that contains a file called file_function.py, i.e.

ABC
    file_function.py

I have a folder in ABC called folder_function that contains a file called main_function.py, i.e.

ABC
    folder_function
        main_function.py

In main_function.py I am calling a function defined in file_function.py called xyz. I am using the following code in main_function.py

from ABC.file_function import xyz

However, this results in ModuleNotFoundError: No module named 'xyz'.

I have tried solutions in other posts with no luck. What could possibly be the issue? Could it be a wrong environment setup? How can I go about debugging this?

Thank you in advance.

Asked By: MathMan 99

||

Answers:

file function is not in folder function (main_function’s parent), so it will give this error. A similar example is that your python program can’t access your photos folder because they are completely different directories!

Try reorganizing the files. If it still doesn’t work, than try this:

from ABC import file_function
from file_function import xyz
Answered By: Pranav

In order for the files or folders of .py files to be callable with the . notation, they need to be modules. A module is defined by its init.py file at every root. The init.py can be empty, but it needs to exist, in this case in the ABC folder and in the folder_function folder.

More Info

What is __init__.py for?

THoughts on how you might want to structure your project and modules.

Answered By: Elmstead

Go to the python download location and search for the python39 file. Inside it you will find pip39. In the address line, click with the mouse to show the full address and something will be close to the following
C:UsersUSER1AppDataLocalProgramsPythonPython39Scripts
Now open the magnifying glass at the bottom left of the screen and type in the search box sysdm.cpl. The system properties box will open, choose advance, scroll down to the bottom of the window and select environment variables
A window will open with two boxes, search in the lower box for the word PATH and double-click on it. A new window will appear. Select the path named PATH and type or paste over it the path shown above, of course, according to what is in the system in all cases, it will start with C : and end with Script then click OK until All windows disappear
Now go back to Terminal and click Run. ModuleNotFoundError will disappear: No module named ‘whatever the module name’ and the script runs successfully

Answered By: HLTC