Python ModuleNotFoundError

In this tutorial we are going to explain you the reason behind  Python ModuleNotFoundError.

Python ModuleNotFoundError

What is Python ModuleNotFoundError?

In Python programming language a set of code to achieve some functionality such as JSON parsing or working with rest servervice are distributed in a package called modules. To use these modules you have to download and install it in your Python environment. If any of the module is not installed and you import in your program then ModuleNotFoundError is thrown.

We are going to explain you this with simple examples.

ModuleNotFoundError: no module named 'mudule_name' -

Modules are essential to python. Modules help the developer to break down the code into multiple small files. This becomes easy for maintaining and reading the code.

A ModuleNotFoundError is one of the basic import errors which is raised when Python cannot import a module successfully.

ModuleNotFoundErrors comes up with user-defined modules. This error occurs when developers import files relatively but which are not allowed or not installed.

ModuleNotFoundError: no module named 'encodings'


Major Reasons of this errors -

  1. Incorrect Module Name -

The first and the most basic reason for this error is incorrect names of the module, so you have to type the exact module name that you had imported.

from flask import Flaks

As you can see, the module's name is incorrect. It's Flaks instead of Flask.

  1. Not Installed Library -

Another reason which can cause this type of error is when the Flask library is not installed in your virtual environment.

For example-

Take a look at a code that uses the Flask package:

from flask import Flask

print('Hello World')

Let’s try to run this code:

Traceback (most recent call last):
  File "", line 1, in <module>
            from flask import Flask
ModuleNotFoundError: No module named 'Flask'

This is happening because flask is an external package, the reason for this error is that the flask library is not installed in a virtual environment.

To solve this error we have to re-import this module by writing this line in terminal:

pip3 install Flask

This will install the Flask module with all of its functions. But you have to make sure that you cannot install modules for python2 using the pip3 command. If you do install it then the python interpreter will not recognize that you have installed a module and it will show the same error.

Conclusion -

The ModuleNotFoundError is raised when Python cannot locate any libraries in your virtual environment. The most common cause of this error is using a module without installing it or importing a module with an incorrect name. If you are using an external module in your python code, you must first make sure that it is correctly installed.

Here more examples of Python: