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:
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
asnumpys
during import - you use an incorrect casing for a module (which still links back to the first point)…for example, spelling
numpy
asNumPy
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
After installing mechanize, I don’t seem to be able to import it.
I have tried installing from pip, easy_install, and via python setup.py install
from this repo: https://github.com/abielr/mechanize. All of this to no avail, as each time I enter my Python interactive I get:
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mechanize
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mechanize
>>>
The installations I ran previously reported that they had completed successfully, so I expect the import to work. What could be causing this error?
Karl Knechtel
61.8k11 gold badges98 silver badges148 bronze badges
asked Jan 12, 2013 at 17:07
8
In my case, it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it!
nbro
15.2k32 gold badges111 silver badges196 bronze badges
answered May 4, 2013 at 17:55
Paul WangPaul Wang
1,6361 gold badge12 silver badges19 bronze badges
7
I had the same problem: script with import colorama
was throwing an ImportError
, but sudo pip install colorama
was telling me «package already installed».
My fix: run pip without sudo: pip install colorama
. Then pip agreed it needed to be installed, installed it, and my script ran. Or even better, use python -m pip install <package>
. The benefit of this is, since you are executing the specific version of python that you want the package in, pip will unequivocally install the package into the «right» python. Again, don’t use sudo
in this case… then you get the package in the right place, but possibly with (unwanted) root permissions.
My environment is Ubuntu 14.04 32-bit; I think I saw this before and after I activated my virtualenv.
wjandrea
27.2k9 gold badges59 silver badges80 bronze badges
answered Jan 14, 2016 at 19:12
Dan HDan H
14k6 gold badges39 silver badges32 bronze badges
3
I was able to correct this issue with a combined approach. First, I followed Chris’ advice, opened a command line and typed ‘pip show packagename’
This provided the location of the installed package.
Next, I opened python and typed ‘import sys’, then ‘sys.path’ to show where my python searches for any packages I import. Alas, the location shown in the first step was NOT in the list.
Final step, I typed ‘sys.path.append(‘package_location_seen_in_step_1’). You optionally can repeat step two to see the location is now in the list.
Test step, try to import the package again… it works.
The downside? It is temporary, and you need to add it to the list each time.
answered Apr 1, 2018 at 20:19
MJ_MJ_
5441 gold badge6 silver badges10 bronze badges
It’s the python path problem.
In my case, I have python installed in:
/Library/Frameworks/Python.framework/Versions/2.6/bin/python,
and there is no site-packages directory within the python2.6.
The package(SOAPpy) I installed by pip is located
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
And site-package is not in the python path, all I did is add site-packages to PYTHONPATH permanently.
-
Open up Terminal
-
Type open .bash_profile
-
In the text file that pops up, add this line at the end:
export PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
-
Save the file, restart the Terminal, and you’re done
desertnaut
57.1k23 gold badges137 silver badges165 bronze badges
answered Apr 22, 2014 at 17:45
user1552891user1552891
5175 silver badges4 bronze badges
3
The Python import mechanism works, really, so, either:
- Your PYTHONPATH is wrong,
- Your library is not installed where you think it is
- You have another library with the same name masking this one
answered Jan 12, 2013 at 17:19
Ali AfsharAli Afshar
40.8k12 gold badges94 silver badges109 bronze badges
8
I have been banging my head against my monitor on this until a young-hip intern told me the secret is to «python setup.py install» inside the module directory.
For some reason, running the setup from there makes it just work.
To be clear, if your module’s name is «foo»:
[burnc7 (2016-06-21 15:28:49) git]# ls -l
total 1
drwxr-xr-x 7 root root 118 Jun 21 15:22 foo
[burnc7 (2016-06-21 15:28:51) git]# cd foo
[burnc7 (2016-06-21 15:28:53) foo]# ls -l
total 2
drwxr-xr-x 2 root root 93 Jun 21 15:23 foo
-rw-r--r-- 1 root root 416 May 31 12:26 setup.py
[burnc7 (2016-06-21 15:28:54) foo]# python setup.py install
<--snip-->
If you try to run setup.py from any other directory by calling out its path, you end up with a borked install.
DOES NOT WORK:
python /root/foo/setup.py install
DOES WORK:
cd /root/foo
python setup.py install
answered Jun 21, 2016 at 22:32
LocaneLocane
2,8562 gold badges24 silver badges34 bronze badges
1
I encountered this while trying to use keyring which I installed via sudo pip install keyring
. As mentioned in the other answers, it’s a permissions issue in my case.
What worked for me:
- Uninstalled keyring:
sudo pip uninstall keyring
- I used sudo’s
-H
option and reinstalled keyring:
sudo -H pip install keyring
answered Sep 4, 2018 at 5:56
blacklegblackleg
3513 silver badges3 bronze badges
In PyCharm, I fixed this issue by changing the project interpreter path.
File -> Settings -> Project -> Project Interpreter
File -> Invalidate Caches…
may be required afterwards.
miken32
41.6k16 gold badges108 silver badges154 bronze badges
answered Feb 27, 2019 at 18:40
Amit DAmit D
611 silver badge2 bronze badges
1
I couldn’t get my PYTHONPATH to work properly. I realized adding export
fixed the issue:
(did work)
export PYTHONPATH=$PYTHONPATH:~/test/site-packages
vs.
(did not work)
PYTHONPATH=$PYTHONPATH:~/test/site-packages
buczek
2,0117 gold badges29 silver badges40 bronze badges
answered Dec 6, 2016 at 16:32
This problem can also occur with a relocated virtual environment (venv).
I had a project with a venv set up inside the root directory. Later I created a new user and decided to move the project to this user. Instead of moving only the source files and installing the dependencies freshly, I moved the entire project along with the venv folder to the new user.
After that, the dependencies that I installed were getting added to the global site-packages
folder instead of the one inside the venv, so the code running inside this env was not able to access those dependencies.
To solve this problem, just remove the venv folder and recreate it again, like so:
$ deactivate
$ rm -rf venv
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt
Karl Knechtel
61.8k11 gold badges98 silver badges148 bronze badges
answered Nov 24, 2020 at 5:34
1
Something that worked for me was:
python -m pip install -user {package name}
The command does not require sudo. This was tested on OSX Mojave.
answered Aug 19, 2019 at 21:35
IShaanIShaan
931 gold badge1 silver badge6 bronze badges
0
In my case I had run pip install Django==1.11
and it would not import from the python
interpreter.
Browsing through pip’s commands I found pip show
which looked like this:
> pip show Django
Name: Django
Version: 1.11
...
Location: /usr/lib/python3.4/site-packages
...
Notice the location says ‘3.4’. I found that the python
-command was linked to python2.7
/usr/bin> ls -l python
lrwxrwxrwx 1 root root 9 Mar 14 15:48 python -> python2.7
Right next to that I found a link called python3
so I used that. You could also change the link to python3.4
. That would fix it, too.
answered Apr 6, 2017 at 14:05
ChrisChris
5,6484 gold badges29 silver badges39 bronze badges
In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.
Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.
answered Apr 26, 2019 at 9:26
jens_lauferjens_laufer
1582 silver badges13 bronze badges
Had this problem too.. the package was installed on Python 3.8.0 but VS Code was running my script using an older version (3.4)
fix in terminal:
py .py
Make sure you’re installing the package on the right Python Version
answered Nov 21, 2019 at 20:39
I had colorama installed via pip and I was getting «ImportError: No module named colorama»
So I searched with «find», found the absolute path and added it in the script like this:
import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama
And it worked.
answered Aug 25, 2020 at 13:01
DimiDakDimiDak
4,7152 gold badges24 silver badges32 bronze badges
I had just the same problem, and updating setuptools
helped:
python3 -m pip install --upgrade pip setuptools wheel
After that, reinstall the package, and it should work fine
The thing is, the package is built incorrectly if setuptools
is old.
answered Jul 28, 2022 at 8:00
Check that you are using the same python version in the interpreter of your IDE or code editor and on your system.
For example, check your python version in the terminal with python3 --version
And check python version for interpreter in VSCode by cmd+shift+p
-> Python: Select interpreter -> select the same version as you see in your terminal.
answered Jan 13 at 14:06
Anna LogachevaAnna Logacheva
7021 gold badge9 silver badges16 bronze badges
This Works!!!
This often happens when module is installed to an older version of python or another directory, no worries as solution is simple.
— import module from directory in which module is installed.
You can do this by first importing the python sys
module then importing from the path in which the module is installed
import sys
sys.path.append("directory in which module is installed")
import <module_name>
answered Jul 4, 2019 at 1:56
If the other answers mentioned do not work for you, try deleting your pip cache and reinstalling the package. My machine runs Ubuntu14.04 and it was located under ~/.cache/pip
. Deleting this folder did the trick for me.
answered Aug 7, 2019 at 1:29
sbrksbrk
1,3181 gold badge16 silver badges25 bronze badges
Also, make sure that you do not confuse pip3
with pip
. What I found was that package installed with pip
was not working with python3
and vice-versa.
answered Nov 14, 2019 at 14:14
I had similar problem (on Windows) and the root cause in my case was ANTIVIRUS software! It has «Auto-Containment» feature, that wraps running process with some kind of a virtual machine.
Symptoms are: pip install somemodule
works fine in one cmd-line window and import somemodule
fails when executed from another process with the error
ModuleNotFoundError: No module named 'somemodule'
answered May 7, 2018 at 6:42
Dima GDima G
1,89518 silver badges22 bronze badges
In my case (an Ubuntu 20.04 VM on WIN10 Host), I have a disordered situation with many version of Python installed and variuos point of Shared Library (installed with pip in many points of the File System). I’m referring to 3.8.10 Python version.
After many tests, I’ve found a suggestion searching with google (but’ I’m sorry, I haven’t the link). This is what I’ve done to resolve the problem :
-
From shell session on Ubuntu 20.04 VM, (inside the Home, in my case /home/hduser), I’ve started a Jupyter Notebook session with the command «jupyter notebook».
-
Then, when jupyter was running I’ve opened a .ipynb file to give commands.
-
First : pip list —> give me the list of packages installed, and, sympy
wasn’t present (although I had installed it with «sudo pip install sympy»
command. -
Last with the command !pip3 install sympy (inside jupyter notebook
session) I’ve solved the problem, here the screen-shot :
-
Now, with !pip list the package «sympy» is present, and working :
answered Jan 9, 2022 at 11:43
In my case, I assumed a package was installed because it showed up in the output of pip freeze
. However, just the site-packages/*.dist-info
folder is enough for pip to list it as installed despite missing the actual package contents (perhaps from an accidental deletion). This happens even when all the path settings are correct, and if you try pip install <pkg>
it will say «requirement already satisfied».
The solution is to manually remove the dist-info
folder so that pip realizes the package contents are missing. Then, doing a fresh install should re-populate anything that was accidentally removed
answered Oct 4, 2022 at 17:59
Addison KlinkeAddison Klinke
9852 gold badges13 silver badges23 bronze badges
When you install via easy_install
or pip
, is it completing successfully? What is the full output? Which python installation are you using? You may need to use sudo
before your installation command, if you are installing modules to a system directory (if you are using the system python installation, perhaps). There’s not a lot of useful information in your question to go off of, but some tools that will probably help include:
-
echo $PYTHONPATH
and/orecho $PATH
: when importing modules, Python searches one of these environment variables (lists of directories,:
delimited) for the module you want. Importing problems are often due to the right directory being absent from these lists -
which python
,which pip
, orwhich easy_install
: these will tell you the location of each executable. It may help to know. -
Use virtualenv, like @JesseBriggs suggests. It works very well with
pip
to help you isolate and manage the modules and environment for separate Python projects.
answered Jan 12, 2013 at 17:26
Ryan ArteconaRyan Artecona
5,9233 gold badges19 silver badges18 bronze badges
0
I had this exact problem, but none of the answers above worked. It drove me crazy until I noticed that sys.path was different after I had imported from the parent project. It turned out that I had used importlib to write a little function in order to import a file not in the project hierarchy. Bad idea: I forgot that I had done this. Even worse, the import process mucked with the sys.path—and left it that way. Very bad idea.
The solution was to stop that, and simply put the file I needed to import into the project. Another approach would have been to put the file into its own project, as it needs to be rebuilt from time to time, and the rebuild may or may not coincide with the rebuild of the main project.
answered Apr 17, 2016 at 19:08
ivanlanivanlan
9596 silver badges8 bronze badges
I had this problem with 2.7 and 3.5 installed on my system trying to test a telegram bot with Python-Telegram-Bot.
I couldn’t get it to work after installing with pip and pip3, with sudo or without. I always got:
Traceback (most recent call last):
File "telegram.py", line 2, in <module>
from telegram.ext import Updater
File "$USER/telegram.py", line 2, in <module>
from telegram.ext import Updater
ImportError: No module named 'telegram.ext'; 'telegram' is not a package
Reading the error message correctly tells me that python is looking in the current directory for a telegram.py
. And right, I had a script lying there called telegram.py and this was loaded by python when I called import
.
Conclusion, make sure you don’t have any package.py
in your current working dir when trying to import. (And read error message thoroughly).
answered Jan 10, 2017 at 7:09
Patrick B.Patrick B.
11.7k8 gold badges57 silver badges100 bronze badges
I had a similar problem using Django. In my case, I could import the module from the Django shell, but not from a .py which imported the module.
The problem was that I was running the Django server (therefore, executing the .py) from a different virtualenv from which the module had been installed.
Instead, the shell instance was being run in the correct virtualenv. Hence, why it worked.
mx0
6,38812 gold badges49 silver badges54 bronze badges
answered May 9, 2019 at 17:41
Most of the possible cases have been already covered in solutions, just sharing my case, it happened to me that I installed a package in one environment (e.g. X
) and I was importing the package in another environment (e.g. Y
). So, always make sure that you’re importing the package from the environment in which you installed the package.
answered Aug 2, 2019 at 16:45
PedramPedram
2,3892 gold badges31 silver badges48 bronze badges
For me it was ensuring the version of the module aligned with the version of Python I was using.. I built the image on a box with Python 3.6 and then injected into a Docker image that happened to have 3.7 installed, and then banging my head when Python was telling me the module wasn’t installed…
36m
for Python 3.6
bsonnumpy.cpython-36m-x86_64-linux-gnu.so
37m
for Python 3.7 bsonnumpy.cpython-37m-x86_64-linux-gnu.so
answered Sep 18, 2019 at 15:43
mkstmkst
5556 silver badges16 bronze badges
4
I know this is a super old post but for me, I had an issue with a 32 bit python and 64 bit python installed. Once I uninstalled the 32 bit python, everything worked as it should.
answered Sep 24, 2019 at 13:18
>>> Насколько я знаю, это импортирует все функции? А если нужно импортировать весь код?
Для модулей только функции и классы нужны. Или вы хотите вызвать и исполнение кода, что не в функциях?
Если так, то при импорте происходит исполнение кода модуля, т.е. что не в функциях сразу же исполняется. Обычно, это как раз, не требуется и соответственно этого пытаются избежать таким способом:
def main():
pass # код который исполняется при запуске, а не при импорте
if __name__ == '__main__':
main()
__name__ будет равен __main__ при прямом запуске этого модуля, и имени файла без расширения (.py) при импорте. Для кругозора прочитайте про пространство имен в Python-е. Спойлер: модули(файлы *.py) в Python такие же объекты как и экземпляры классов, и работаем с ними соответственно
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
from tkinter import * import numpy as np import random canvas_width = 700 canvas_height = 500 brush_size = 3 color = "black" def create_point(): chislo = message.get() n = int(chislo) - 1 x1 = random.randrange(start=1, stop=700) y1 = random.randrange(start=1, stop=500) for i in range(n): x2 = random.randrange(start=1, stop=700) y2 = random.randrange(start=1, stop=500) w.create_line(x1, y1, x2, y2, fill=color) x1 = x2 y1 = y2 root = Tk() root.title("Точки-ломаная-сгладить") message = StringVar() message_entry = Entry(textvariable=message) w = Canvas(root, width=canvas_width, height=canvas_height, bg="white") w.bind("<B1-Motion>") create_btn = Button(text="Соединить точки", width=14, command=lambda: create_point()) b_btn = Button(text="Сгладить ломаную", width=15, command=lambda: color_change("yellow")) clear_btn = Button(text="Очистить", width=10, command=lambda: w.delete("all")) w.grid(row=2, column=0, columnspan=7, padx=5, pady=5, sticky=E+W+S+N) w.columnconfigure(6, weight=1) w.rowconfigure(2, weight=1) message_entry.grid(row=0, column=2) create_btn.grid(row=0, column=3) b_btn.grid(row=0, column=4) clear_btn.grid(row=0, column=5, sticky=W) root.mainloop() |