Module not found error python

When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python? As the name implies, this error occurs when you're trying to access or use a module that cannot be found. In the case of the title, the "module named Python" cannot be found. Python here can be any module. Here's an error when I try to import a numpys module that cannot be found: import numpys

ModuleNotFoundError: no module named Python Error [Fixed]

When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python?

As the name implies, this error occurs when you’re trying to access or use a module that cannot be found. In the case of the title, the «module named Python» cannot be found.

Python here can be any module. Here’s an error when I try to import a numpys module that cannot be found:

import numpys as np

Here’s what the error looks like:

image-341

Here are a few reasons why a module may not be found:

  • you do not have the module you tried importing installed on your computer
  • you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed)…for example, spelling numpy as numpys during import
  • you use an incorrect casing for a module (which still links back to the first point)…for example, spelling numpy as NumPy during import will throw the module not found error as both modules are «not the same»
  • you are importing a module using the wrong path

How to fix the ModuleNotFoundError in Python

As I mentioned in the previous section, there are a couple of reasons a module may not be found. Here are some solutions.

1. Make sure imported modules are installed

Take for example, numpy. You use this module in your code in a file called «test.py» like this:

import numpy as np

arr = np.array([1, 2, 3])

print(arr)

If you try to run this code with python test.py and you get this error:

ModuleNotFoundError: No module named "numpy"

Then it’s most likely possible that the numpy module is not installed on your device. You can install the module like this:

python -m pip install numpy

When installed, the previous code will work correctly and you get the result printed in your terminal:

[1, 2, 3]

2. Make sure modules are spelled correctly

In some cases, you may have installed the module you need, but trying to use it still throws the ModuleNotFound error. In such cases, it could be that you spelled it incorrectly. Take, for example, this code:

import nompy as np

arr = np.array([1, 2, 3])

print(arr)

Here, you have installed numpy but running the above code throws this error:

ModuleNotFoundError: No module named "nompy"

This error comes as a result of the misspelled numpy module as nompy (with the letter o instead of u). You can fix this error by spelling the module correctly.

3. Make sure modules are in the right casing

Similar to the misspelling issue for module not found errors, it could also be that you are spelling the module correctly, but in the wrong casing. Here’s an example:

import Numpy as np

arr = np.array([1, 2, 3])

print(arr)

For this code, you have numpy installed but running the above code will throw this error:

ModuleNotFoundError: No module named 'Numpy'

Due to casing differences, numpy and Numpy are different modules. You can fix this error by spelling the module in the right casing.

4. Make sure you use the right paths

In Python, you can import modules from other files using absolute or relative paths. For this example, I’ll focus on absolute paths.

When you try to access a module from the wrong path, you will also get the module not found here. Here’s an example:

Let’s say you have a project folder called test. In it, you have two folders demoA and demoB.

demoA has an __init__.py file (to show it’s a Python package) and a test1.py module.

demoA also has an __init__.py file and a test2.py module.

Here’s the structure:

└── test
    ├── demoA
        ├── __init__.py
    │   ├── test1.py
    └── demoB
        ├── __init__.py
        ├── test2.py

Here are the contents of test1.py:

def hello():
  print("hello")

And let’s say you want to use this declared hello function in test2.py. The following code will throw a module not found error:

import demoA.test as test1

test1.hello()

This code will throw the following error:

ModuleNotFoundError: No module named 'demoA.test'

The reason for this is that we have used the wrong path to access the test1 module. The right path should be demoA.test1. When you correct that, the code works:

import demoA.test1 as test1

test1.hello()
# hello

Wrapping up

For resolving an imported module, Python checks places like the inbuilt library, installed modules, and modules in the current project. If it’s unable to resolve that module, it throws the ModuleNotFoundError.

Sometimes you do not have that module installed, so you have to install it. Sometimes it’s a misspelled module, or the naming with the wrong casing, or a wrong path. In this article, I’ve shown four possible ways of fixing this error if you experience it.

I hope you learned from it :)



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

В Python может быть несколько причин возникновения ошибки ModuleNotFoundError: No module named ...:

  • Модуль Python не установлен.
  • Есть конфликт в названиях пакета и модуля.
  • Есть конфликт зависимости модулей Python.

Рассмотрим варианты их решения.

Модуль не установлен

В первую очередь нужно проверить, установлен ли модуль. Для использования модуля в программе его нужно установить. Например, если попробовать использовать numpy без установки с помощью pip install будет следующая ошибка:

Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'numpy'

Для установки нужного модуля используйте следующую команду:

pip install numpy
# или
pip3 install numpy

Или вот эту если используете Anaconda:

conda install numpy

Учтите, что может быть несколько экземпляров Python (или виртуальных сред) в системе. Модуль нужно устанавливать в определенный экземпляр.

Конфликт имен библиотеки и модуля

Еще одна причина ошибки No module named — конфликт в названиях пакета и модуля. Предположим, есть следующая структура проекта Python:

demo-project
 └───utils
         __init__.py
         string_utils.py
         utils.py

Если использовать следующую инструкцию импорта файла utils.py, то Python вернет ошибку ModuleNotFoundError.


>>> import utils.string_utils
Traceback (most recent call last):
File "C:demo-projectutilsutils.py", line 1, in
import utils.string_utils
ModuleNotFoundError: No module named 'utils.string_utils';
'utils' is not a package

В сообщении об ошибке сказано, что «utils is not a package». utils — это имя пакета, но это также и имя модуля. Это приводит к конфликту, когда имя модуля перекрывает имя пакета/библиотеки. Для его разрешения нужно переименовать файл utils.py.

Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.

Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester.

Traceback (most recent call last):
   File "C:demo-projectvenv
Libsite-packages
         scipy_lib_numpy_compat.py", line 10, in
     from numpy.testing.nosetester import import_nose
 ModuleNotFoundError: No module named 'numpy.testing.nosetester'

Ошибка ModuleNotFoundError возникает из-за того, что модуль numpy.testing.nosetester удален из библиотеки в версии 1.18. Для решения этой проблемы нужно обновить numpy и scipy до последних версий.

pip install numpy --upgrade
pip install scipy --upgrade 

I’m trying to debug some python code using VS code. I’m getting the following error about a module that I am sure is installed.

Exception has occurred: ModuleNotFoundError
No module named 'SimpleITK'
  File "C:UsersMidoDesktopProstateX-projectsrc1-preprocessing3_resample_nifti.py", line 8, in <module>
    import SimpleITK as sitk

I installed the module using

sudo pip install SimpleITK

I know that it was installed because I was getting a similar error when I ran the code through the command line, and it was fixed by doing the above. I don’t understand why VS code does not recognize that

asked Jun 19, 2019 at 0:15

An Ignorant Wanderer's user avatar

1

After installing a new module via pip reloading vscode may work if vscode doesn’t recognize it. To do this, make sure that the module is installed inside the virtual environment by creating and activating a virtualenv:

python3 -m venv env
source env/bin/activate

Make sure to use the correct way of installing a module with pip:

python3 -m pip install {new_module}

Replace the string «{new_module}» with your module name. After that, make sure to reload vscode by clicking Ctrl+Shift+P, and selecting Reload window.

Now vscode will know the new module and autocompletion works.

Hagbard's user avatar

Hagbard

3,2393 gold badges25 silver badges61 bronze badges

answered Jul 14, 2020 at 8:01

EsmaeelE's user avatar

1

sudo pip install is most likely installing globally into a Python interpreter that is different than the one that you have selected in VS Code. Please select the Python interpreter you want to use and then install explicitly using that interpreter (if you’re not using a virtual environment then use something like /path/to/python -m pip install SimpleITK, although I strongly recommend using a virtual environment and to not install packages globally).

answered Jun 19, 2019 at 20:28

Brett Cannon's user avatar

Brett CannonBrett Cannon

13.4k1 gold badge43 silver badges38 bronze badges

2

In Mac, correctly selecting the Python Interpreter worked for me:

From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

No interpreter selected

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Source :VS Code Select Interpreter

answered Feb 16, 2021 at 1:45

Knectt's user avatar

KnecttKnectt

3112 silver badges5 bronze badges

0

This error: your vscode use other python version. This solution change vscode use current python.

  1. In terminal find current python version:

    py —version

  2. In vscode Press Ctrl+Shift+P then type:

    Python: Select Interpreter

  3. Select current python version

answered Oct 26, 2021 at 13:39

Dũng IT's user avatar

Dũng ITDũng IT

2,52328 silver badges29 bronze badges

1

There are a lot of proposed answers that suggest changing the launch.json or the settings.json file. However, neither of these solutions worked for me.

My situation:

  1. Is Python environment selected? yes
  2. Does the Terminal recognize Python environment? yes
  3. Can I run the Python code from the activated Terminal? yes
  4. Does the code run w/o error when I use «Start Debugging»? yes
  5. Does the code run when I click «Run Code»? no

The only solution that worked for me is to:

  1. Open Windows Terminal (or cmd)
  2. Activate environment: conda activate <environment_name>
  3. Open Visual Studio Code from Terminal: code

Then, «Run Code» (#5) works without any issues.

Source:
«module not found error» in VS Code using Conda — l3d00m’s answer

answered Jan 27, 2021 at 10:55

datalifenyc's user avatar

datalifenycdatalifenyc

1,90817 silver badges16 bronze badges

1

Try running pip list in VS Code to check if the module is installed, next check if your python version is correct/supports that version of SimpleITK. It may be a problem with the python interpreter that you are using for VS Code (ie. the module may be installed on a different python instance than the one your VS Code is using)

answered Jun 19, 2019 at 0:57

Kyr's user avatar

KyrKyr

551 silver badge7 bronze badges

2

Is Python environment selected?
Does the Terminal recognize the Python environment?
Can I run the Python code from the activated Terminal?
Does the code run w/o error when I use «Start Debugging»?

if the answer to the above is «yes.»

Then,
Try running the Code using the option «Run python file in terminal» (in code runner extension). And assign a new shortcut for that for future use…

answered Mar 24, 2021 at 10:43

Jnaneswar's user avatar

How to fix module not found error in Visual Studio code?
To Solve VSCode ModuleNotFoundError: No module named X Error Make sure you are running from the package folder (not from package/module ) if you want import module. calculations to work. You can also set the PYTHONPATH environment variable to the path to the package folder.

answered Nov 3, 2021 at 17:28

Reza Mahmoud zadeh's user avatar

Once you have created a virtual environment, and installed your required packages in that environment, close VS code. For Windows platform, open command prompt and navigate to the folder where your virtual env folder is created. And then launch VS code from there using the command code .

For ex: My virtual env name is .imgenv, and its inside C:py_stuffprojects
So, I navigate to C:py_stuffprojects and then type code .

Now, your VS code should recognize the packages !

answered Jan 19 at 12:51

Bishal's user avatar

BishalBishal

651 silver badge8 bronze badges

I just ran into the same issue. I found that if I selected all text before shift enter the script would compile as a file instead of as a single line.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Jul 14, 2021 at 1:45

DMF3K's user avatar

I had the same problem. I bet you have a shebang statement at the top of your file.
If you do.

  1. Visual Studios settings
  2. Under «Code-runner->Code-runner: Respect Shebang» section or just do a search for «Code-runner: Respect Shebang»
  3. Uncheck weather to respect Shebang to run code.

Now it will run under the virtual environment and find the modules that you installed using pip! :)

answered Oct 1, 2021 at 17:37

wildernessfamily's user avatar

I struggled with this for a very long time, and had tried almost every other answer. I wasn’t using pip, so that wasn’t the issue. But still VS Code wasn’t finding the modules that were installed in the Selected Interpreter.

Ultimately it came down to old conflicts that existed because I switched to miniconda, and VS Code was still looking for anaconda3.

I completely wiped VS Code and its associated files (cache, preference files, etc.) from my machine (some instructions), and installed a clean version.

This now syncs as expected with miniconda.

answered Nov 13, 2021 at 0:57

Adam_G's user avatar

Adam_GAdam_G

6,98419 gold badges81 silver badges146 bronze badges

If you have different python versions installed, be sure you install module with right one.

python -m pip install <module>

or

python3 -m pip install <module>

answered Nov 27, 2021 at 17:23

Aidar Gatin's user avatar

Aidar GatinAidar Gatin

6977 silver badges9 bronze badges

Run your environment from a directory not in the users directory. I solved my problem running my environment from C:CodeProjectA

I discovered my problem by running:

IMPORT os

Mycwd = os.getcwd()
PRINT(Mycwd)

answered Jul 23, 2022 at 4:09

Keybonesabi's user avatar

.venv/Lib/SitePackages is the default directory where Vscode looks for Modules.

This directory is automatically created on creating .venv via the command Pallete.

External modules installed via pip are placed in this directory by default.

Place self created modules inside this folder manually.

enter image description here

answered Nov 12, 2022 at 6:26

srt111's user avatar

srt111srt111

94711 silver badges17 bronze badges

Faced similar issue and here is how I fixed it. Remember that there are multiple ways to run your code in VS code. And for each way you may end up with different interpreters and environments. For example:
enter image description here


1. Creating virtual env and installing libraries

  • In my case I opted into creating virtual environment and doing so outside of VS Code using command prompt:
    python -m venv .plotting_test
    enter image description here

  • Following that I activated it:
    .plotting_testScriptsactivate.bat

  • Following that I installed additional libraries:
    python -m pip install matplotlib

  • Following that I made sure to see it was all installed ok:
    python -m pip list
    enter image description here

  • And I also checked where for current directory:
    cd
    enter image description here


2. Point VS Code & VS Code Code Runner to virtual environment

  • Opened vs code, closed previous workspaces, opened new folder, created test.py as I was starting new. Pressed ctrl + shift + p. Selected «`Python: Select Interpreter«:
    enter image description here

  • Followed by + Enter interpreted path
    enter image description here

  • Navigated to directory from last step from section 1. Found my virtual environment folder created in step one and pointed VS code to that version’s python.exe in Scripts:
    enter image description here

  • Verified I am pointed to such:
    enter image description here

  • Saved as workspace so that I can create default workspace settings for this project:
    enter image description here

  • In workspace settings files defined paths to my virtual environment created n step 1 for workspace interpreter & CODE RUNNER(!):
    enter image description here

    "settings": {
            "python.defaultInterpreterPath": "C:/Users/yyguy/.plotting_test/Scripts/python.exe",
            "code-runner.executorMap": {"python": "call C:/Users/yyguy/.plotting_test/Scripts/activate.bat && python -u"}
    }
}
  • Reloaded window just to make sure (ctrl + shift + p) = «Developer: Reload Window»
    enter image description here

  • Now run code and run python file should be execute under your specified envs:
    enter image description here

enter image description here

answered Dec 16, 2022 at 13:36

Yev Guyduy's user avatar

Yev GuyduyYev Guyduy

1,16110 silver badges12 bronze badges

Что означает ошибка ModuleNotFoundError: No module named

Что означает ошибка ModuleNotFoundError: No module named

Python ругается, что не может найти нужный модуль

Python ругается, что не может найти нужный модуль

Ситуация: мы решили заняться бигдатой и обработать большой массив данных на Python. Чтобы было проще, мы используем уже готовые решения и находим нужный нам код в интернете, например такой:

import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)
zeros = np.zeros((5, 4))
lin = np.linspace(1, 10, 20)

Копируем, вставляем в редактор кода и запускаем, чтобы разобраться, как что работает. Но вместо обработки данных Python выдаёт ошибку:

❌ModuleNotFoundError: No module named numpy

Странно, но этот код точно правильный: мы его взяли из блога разработчика и, по комментариям, у всех всё работает. Откуда тогда ошибка?

Что это значит: Python пытается подключить библиотеку, которую мы указали, но не может её найти у себя.

Когда встречается: когда библиотеки нет или мы неправильно написали её название.

Что делать с ошибкой ModuleNotFoundError: No module named

Самый простой способ исправить эту ошибку — установить библиотеку, которую мы хотим подключить в проект. Для установки Python-библиотек используют штатную команду pip или pip3, которая работает так: pip install <имя_библиотеки>. В нашем случае Python говорит, что он не может подключить библиотеку Numpy, поэтому пишем в командной строке такое:

pip install numpy

Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.

Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:

Что означает ошибка ModuleNotFoundError: No module named

А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.

Вёрстка:

Кирилл Климентьев

Python-Module-Not-Found-Error

This python tutorial help to solve “Module Not Found Error” for python. The reasons for this error and how to solve it.

We will discussed one by one possible reason for module not found.

We ill cover following points here:

  1. Python module is no imported
  2. Python module is not Installed
  3. The name of the module is incorrect
  4. The path of the module is incorrect

Python module is no imported

The module method has been used but forget to include main module, We need to import that module.

app.py

print(math.pi)

We will get below error as a output:

Traceback (most recent call last):
  File "<string>", line 3, in <module>
NameError: name 'math' is not defined

Correct way to use math module witn in app.py file:

import math
print(math.pi)

Output:

3.141592653589793

Python module is not Installed

You can get the issue when you are trying to import a module of a library which not installed in your virtual environment. So before importing a library’s module, you need to install it with the pip command.

Let’s import an module(requests) into app.py file which is not installed into our virtual environment:

r = requests.get('http://dummy.restapiexample.com/api/v1/employee/2')

print(r)

The output:

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  ModuleNotFoundError: No module named 'requests'

Now, let’s install the library:

pip install requests

The name of the module is incorrect

The other possible reason might be module name is incorrect in import. We just make sure module name is correct into import syntax.

For example, let’s try to import math module with extra a and see what will happen:

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

As you can see above console output, The python does not found named ‘matha’ module.

path of the module is incorrect

We have import module into the python application but path is not correct, we need to set correct path of missed module.

Python Folder Structure:

app.py
services
---gapi.py

Let’s, we will import gapi.py as like below:

app.py

import gapi.py #incorrect

We will get output as like below:

Output:

ModuleNotFoundError: No module named 'gapi'

Correct way to import a file into app.py:

import services.gapi.py #correct

Overview

Traceback (most recent call last):
  File "afile.py", line 1, in <module>
    import doesnotexist
ImportError: No module named doesnotexist

When you run a Python application, script, or interactive terminal, you see an error that looks like the above.

Initial Steps Overview

  1. Check module exists

  2. Check command line loading

  3. Check module is correctly set up

  4. Check installation method

  5. Module in a subfolder?

  6. Double import trap?

  7. Virtualenv activated?

Detailed Steps

1) Check module exists

First, determine that the module exists on your system, and where.

There are a number of ways to determine this if you are unsure how to proceed.

1.1) Use locatedb

If you have a system with locatedb installed on it and have access to update it, and are looking for a module called modulename, you can try running:

sudo updatedb
locate modulename | grep -w modulename$

which should output possible locations where the modules is installed.

If locatedb is not installed, or not up to date/under your control, then you can try and use find to search for the module in a similar way. Or you can look at using other tools available to you in your environment.

1.2) Use the sys.path

If you know the version of Python you are using on the command line is correct (see step 2.1), then you can check the default path where Python modules are searched for by adding the following to the file that is trying to load the module:

import sys
print("sys.path:n" + "n".join(sys.path))
exit()

You could run this from the Python Interpreter, however doing so will lead to the first entry being blank instead of showing the current working directory that your script would check. The output will show you the folders that python searches through looking for Python packages in their immediate subfolders.

The sys.path value is figured out on startup by Python running a site.py located under the Python installation. This dynamically picks up relevant folders based on the code in that file.

2) Check command line

After you have determined that the module exists, check that the module loads when you run Python on the command line.

You can do this by running Python on the command line, and typing at the prompt:

if the prompt returns without a message, then the module was loaded OK.

If this doesn’t solve your problem because the program you were running was not running on the command line, OR you still the same error, consider the following possibilities:

2.1) You are using the wrong Python version

It may be that you are using Python version 2.x instead of 3.x, or vice versa. Or even a different minor or point version of Python. Different Python versions can look in different locations for their libraries, and so using the wrong version can mean that the library can’t be found.

You can check your version directly from your script by adding the following snippet just above your failing import:

import sys
print("sys.version: " + sys.version)
print(str(sys.version_info))
exit()

If your Python module was in a folder with a version number in it, eg:

/Library/Python/3.7/site-packages

then this may be the problem you are facing.

2.2) Your PYTHONPATH is misconfigured

If your module is in a non-standard location, then it’s possible your PYTHONPATH needs to be configured, or reconfigured.

For more information on this, see here.

3) Check the module is correctly set up

If you are using a pre-3.3 version of Python, then it is a requirement that a Python module contains a file called __init__.py.

The inclusion of the file is often forgotten about when creating modules on-the-fly, so is a frequent cause of failure.

You may also want to consider whether the user you are running as has the right permissions to access the files and folders (see step 4).

4) Check installation method

If you installed the module using pip or some similar package management method, then consider:

  • Did you install as the root user (using sudo or similar)

  • Did you install as a user other than the user running the Python import?

5) Module in a subfolder?

Is the module you are trying to load in a subfolder?

If so, you may need to more carefully qualify your module import. See here for more background.

6) Double import trap?

If you have PYTHONPATH set in your environment, or are adding to your sys.path within your code or configuration, you may be falling victim to this trap, which can cause havoc with relative imports and the like. See here for more background.

7) Virtualenv activated?

If your python code runs in a virtualenv, you may need to activate it for this error to be resolved. See solution A for more on this.

Solutions List

A) Activate your virtualenv

Solutions Detail

A) Activate your virtualenv

Typically, this will require you to run:

virtualenv .
source bin/activate

before you re-run your code.

Check Resolution

The application or steps followed at the start no longer result in an error.

Further Information

This is an excellent resource in this context, for background and troubleshooting: Import traps

General primer on Python packages:

  • Python packages, v2

  • Python packages, v3

Virtualenvs

Owner

Ian Miell

Понравилась статья? Поделить с друзьями:
  • Module not found error pygame
  • Module not found error pycharm
  • Module not found error no module named pip
  • Module not found error no module named numpy
  • Module library initialization error