Modulenotfounderror python как исправить

Что означает ошибка 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 может быть несколько причин возникновения ошибки 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 

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

ModuleNotFoundError: No module named in Python occurs when:

  • The name of the module is incorrect
  • The path of the module is incorrect
  • The Library is not installed
  • The module is unsupported
  • Python 2 instead of Python 3

In this article, We’ll discuss the reasons and the solutions for the ModuleNotFoundError error.

1. The name of the module is incorrect

The first reason for ModuleNotFoundError: No module named is the module name is incorrect. For example, let’s try to import the os module with double «s» and see what will happen:

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

As you can see, we got ModuleNotFoundError: No module named ‘oss.’ To solve the error, make sure that you use the correct module name.

Let’s import the module with the correct name.

>>> import os
>>> 

As you can see, the error is solved.

2. The path of the module is incorrect

The Second reason is the path of the local module you want to import is incorrect. for example, let’s see a directory structure 

Project structure:


core.py
folder_1
---my_module.py

In this folder, we’ve:

  • core.py: is the file that will execute
  • folder_1: folder contains my_module.py

Now in core.py, let’s try to import my_module.py

core.py


import my_module #incorrect

Output:

ModuleNotFoundError: No module named 'my_module'

As you can see, we got the error because my_module.py is not in the path that we’ve executed core.py. We need to define the module’s path in the following example to solve the error.

core.py


import folder_1.my_module #correct

Output:

...Program finished with exit code 0

Now we’ve imported m_module successfully.

3. The library is not installed

Also, you can get the ModuleNotFoundError: No module named issue if you are trying to import a library module that is not installed in your virtual environment or computer.

So before importing a library’s module, you need to install it with any package-management system.

For example, let’s try to import the Beautifulsoup4 library that’s not installed in my virtual environment.

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

Now, let’s install the library and try to re-import it:

pip install beautifulsoup4
Collecting beautifulsoup4
  Using cached https://files.pythonhosted.org/packages/d1/41/e6495bd7d3781cee623ce23ea6ac73282a373088fcd0ddc809a047b18eae/beautifulsoup4-4.9.3-py3-none-any.whl
Requirement already satisfied: soupsieve>1.2; python_version >= "3.0" in /home/py/Desktop/seo_pro/seo_env/lib/python3.6/site-packages (from beautifulsoup4) (1.9.5)
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.9.3

Re-importing:

>>> from bs4 import BeautifulSoup
>>> 

As you can see, after installing the package, the program is working.

4. The module is unsupported

When a library releases a new update, new modules are added, and others are dropped to support it.

If you try to import a module that is n unsupported by the library, you will get ModuleNotFoundError: No module named.

To ensure the module is supported, go to the package documentation and check if the module is available or not.

5. Python 2 instead of Python 3

As you know, Some Python libraries no longer support Python 2. For that reason, you’ll get the ModuleNotFoundError error if you execute a module that does not support Python 2 with Python 2.

To solve the error:

First, let’s check our python version using these two commands:

python -V
# Python 2.7.18

python3 -V
# Python 3.9.5

In my case, Python 3 is on the python3 command, So I will execute the program using python3. If Python3 is not found on your device, Install Python on Windows, Mac, and Linux.

Conclusion

In conclusion, To solve the  ModuleNotFoundError: No module named:

  1. Ensure the name of the module is incorrect
  2. Ensure the path of the module is incorrect
  3. Ensure the Library is installed
  4. Ensure the module is supported
  5. Ensure using Python 3

Finally, I hope your problem has been fixed.

  1. Use the Correct Module Name to Solve ModuleNotFoundError in Python
  2. Use the Correct Syntax to Solve ModuleNotFoundError in Python

Solve ModuleNotFoundError in Python

Modules are important for developing Python programs. With modules, we can separate different parts of a codebase for easier management.

When working with modules, understanding how they work and how we can import them into our code is important. Without this understanding or mistakes, we may experience different errors.

One example of such an error is ModuleNotFoundError. In this article, we will discuss the way to resolve ModuleNotFoundError within Python.

Use the Correct Module Name to Solve ModuleNotFoundError in Python

Let’s create a simple Python codebase with two files, index.py and file.py, where we import file.py into the index.py file. Both files are within the same directory.

The file.py file contains the code below.

class Student():
    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

The index.py file contains the code below.

import fiIe
studentOne = fiIe.Student("Isaac", "Asimov")
print(studentOne.lastName)

Now, let’s run index.py. The output of our code execution is below.

Traceback (most recent call last):
  File "c:UsersakinlDocumentsPythonindex.py", line 1, in <module>
    import fiIe
ModuleNotFoundError: No module named 'fiIe'

We have a ModuleNotFoundError. If you look closely, you will notice that the import statement has a typographical error where file is written as fiIe with the l replaced with a capital I.

Therefore, if we use the wrong name, a ModuleNotFoundError can be thrown at us. Be careful when writing your module names.

Now, let’s correct it and get our code running.

import file
studentOne = file.Student("Isaac", "Asimov")
print(studentOne.lastName)

The output of the code:

Also, we could rewrite the import statement using the from keyword and import just the Student class. This is useful for cases where we don’t want to import all the functions, classes, and methods present within the module.

from file import Student
studentOne = Student("Isaac", "Asimov")
print(studentOne.lastName)

We will get the same output as the last time.

Use the Correct Syntax to Solve ModuleNotFoundError in Python

We can get a ModuleNotFoundError when we use the wrong syntax when importing another module, especially when working with modules in a separate directory.

Let’s create a more complex codebase using the same code as the last section but with some extensions. To create this codebase, we need the project structure below.

Project/
	data/
		file.py
		welcome.py
	index.py

With this structure, we have a data package that houses the file and welcome modules.

In the file.py file, we have the code below.

class Student():
    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

In the welcome.py, we have the code below.

def printWelcome(arg):
    return "Welcome to " + arg

The index.py contains code that tries to import file and welcome and uses the class Student and function printWelcome.

import data.welcome.printWelcome
import data.file.Student

welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")

print(welcome)
print(studentOne.firstName)

The output of running index.py:

Traceback (most recent call last):
  File "c:UsersakinlDocumentsPythonindex.py", line 1, in <module>
    import data.welcome.printWelcome
ModuleNotFoundError: No module named 'data.welcome.printWelcome'; 'data.welcome' is not a package

The code tried to import the function printWelcome and class Student using the dot operator directly instead of using the from keyword or the __init__.py for easy binding for submodules. By doing this, we have a ModuleNotFoundError thrown at us.

Let’s use the correct import statement syntax to prevent ModuleNotFoundError and import the function and class directly.

from data.file import Student
from data.welcome import printWelcome

welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")

print(welcome)
print(studentOne.firstName)

The output of the code:

We can bind the modules (file and welcome) within the data package to its parent namespace. To do this, we need the __init__.py file.

In the __init__.py file, we import all the modules and their functions, classes, or objects within the package to allow easy management.

from .file import Student
from .welcome import printWelcome

Now, we can write our index.py more succinctly and with a good binding to the parent namespace, data.

from data import Student, printWelcome

welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")

print(welcome)
print(studentOne.firstName)

The output will be the same as the last code execution.

To prevent the ModuleNotFoundError error message, ensure you don’t have a wrong import statement or typographical errors.

Понравилась статья? Поделить с друзьями:
  • Теорема пифагора формулы как найти катеты
  • Как найти осла в игре что это
  • Как найти долю в дороге
  • Dwarf fortress как найти своих
  • Как найти объем контура