- Python “No Module Named” Import Error
- What does this Error mean?
- Library not installed
- Multiple Python Installations
- Incorrect Library name
- Importing a file
- Решение ошибки «ModuleNotFoundError: No module named ‘…’»
- Модуль не установлен
- Конфликт имен библиотеки и модуля
- Конфликт зависимостей модулей Python
- Что означает ошибка ModuleNotFoundError: No module named
- Что делать с ошибкой ModuleNotFoundError: No module named
Python “No Module Named” Import Error
As someone who owns a Coding website and blog, I tend to keep an eye out on the Programming community and their troubles. If I notice enough demand for a certain topic or question, I’ll create a tutorial or make a post about it.
One day while going through a list of popular googles searches, I happened to notice an unusually large number of people making searches like “no module name xxx“. For some Python libraries, there would be over 10k monthly searches like this. If one were to add them all up, they would probably number well over 100k per month.
At any rate, I was quite surprised, and have decided to make this article as a guide, explaining this error, how to fix it and how to avoid running into this in the future.
What does this Error mean?
As the name implies, this error occurs when Python is unable to locate a module that you have tried importing. And as expected of the Python interpreter, it immediately returns an exception, ModuleNotFoundError and shuts the program down.
So why was Python unable to find this module? Let’s assume you were trying to import this library called fly. You used the import fly statement, but of course, since no module called fly exists, the following error was thrown.
Traceback (most recent call last): File "C:\Users\CodersLegacy\Desktop\script.py", line 1, in import fly ModuleNotFoundError: No module named 'fly'
We’ll now proceed to examine every possible scenario in which this error can occur and how to fix it.
Library not installed
This is by far the most common reason. You’ve tried to import a library that you saw someone use in a YouTube tutorial, but the problem here is that Python does not come with all these libraries pre-installed and downloaded. Only a certain number of libraries, known as the Standard library can be imported directly. Popular examples of such libraries are DateTime and Tkinter.
So what do you do now? Well, you head over to the command prompt, navigate to your Python installation and use the Python package installer pip to download the library of your choice. It’s a very simple command, pip install .
Since I have the path to my Python.exe added to the list of default paths, I don’t have to manually navigate to it. If you were confused about any step in this process, head over to the Python setup guide where it’s discussed in detail.
Making sure you’re in the correct directory is of utmost importance. Most people make this mistake and simply try to call the pip install from the default location on the command prompt. You must first navigate to the folder with your Python.exe and then call the command. If you don’t know how to navigate the command prompt, you’ll have to look it up.
Multiple Python Installations
One issue that can complicate things is if you have multiple Python installations on your computer. And this is easily possible. As I’m writing this, I currently have two Python installations myself (accidentally of course). The first I happened to download when I was setting up Visual Studio, which would serve as my IDE for Python for a good while. My Python.exe file path looks something like this.
C://Program Files/Microsoft Visual Studio/Python37
Now, every time I download a library, it’s installed in the above folder. As a result only the python.exe in this folder can access those libraries. The second Python installation of mine was done through the regular method, and is stored elsewhere. As a result, it cannot access the libraries installed with the first Python installation.
Now how is this relevant to this article? Well, if you have multiple python installations, there’s a good chance you’ve gotten confused between the two and are importing the library from the wrong place. If this is the case, before rushing over to google this error, make sure that the library is installed at the Python installation you’re currently using.
Incorrect Library name
While extremely unlikely, there is a chance you messed up the library names. I know for fact that sometimes the actual name of a library and the name used to install the library can be a bit different.
For instance the popular web scrapper library BeautifulSoup is installed and imported with the name bs4 . Some people may try to download or import it using the name BeautifulSoup, and that would return an error.
There’s a simple to find the name through which a library is imported. Do a google search like Python numpy and click on the first tutorial for it. 9 times out of 10 there will be a small section at the top where they mention how to install the library.
Importing a file
Unbeknownst to many python programmers, you can actually import another python file into your python program. Why we do this is a story for another article, where it’s explained in greater detail. But for now, we’ll just cover the import problems that may be caused while doing this.
Let’s assume you’re trying to import a file called data.py . To import this correctly, you must use import data . Note the lack of an extension. Secondly, it must be in the same directory as the file you’re importing it into. If the Python files are not in the same directory, a no module named data error will pop up.
You can still import a file even if it’s in another directory, but the process is a bit shaky, so its best to avoid it.
One final tip. Be careful while naming your files. Do not use the names of any libraries, like numpy.py or csv.py . If you do so, and simultaneously import that same library, Python will get confused between the two and try importing the file instead of the library.
I think that just about covers every scenario in which you could possibly face this error. Hopefully you’ve learnt something from this article and won’t have to worry about this error in the future.
BONUS: If you are interested in learning more about importing modules in Python, check out this tutorial which teaches you how to import a module using a user-input string.
This marks the end of the Python “no module named” error Article. Any suggestions or contributions for CodersLegacy are more than welcome. Relevant questions regarding the article can be asking in the comments section below.
Follow us
Решение ошибки «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:
Учтите, что может быть несколько экземпляров 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-project\utils\utils.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
Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.
Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester .
Traceback (most recent call last): File "C:\demo-project\venv\ Lib\site-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. Чтобы было проще, мы используем уже готовые решения и находим нужный нам код в интернете, например такой:
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, поэтому пишем в командной строке такое:
Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.
Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi . Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:
А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.
![]()
![]()
![]()
В «Яндекс Практикуме» можно стать разработчиком, тестировщиком, аналитиком и менеджером цифровых продуктов. Первая часть обучения всегда бесплатная, чтобы попробовать и найти то, что вам по душе. Дальше — программы трудоустройства.