Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Module Not Found

Tags:

python

module

I am a beginner with Python. Before I start, here's my Python folder structure

-project ----src ------model --------order.py ------hello-world.py 

Under src I have a folder named model which has a Python file called order.py which contents follow:

class SellOrder(object):     def __init__(self,genericName,brandName):         self.genericName = genericName         self.brandName = brandName 

Next my hello-world.py is inside the src folder, one level above order.py:

import model.order.SellOrder  order = SellOrder("Test","Test")  print order.brandName 

Whenever I run python hello-world.py it results in the error

Traceback (most recent call last):   File "hello-world.py", line 1, in <module>     import model.order.SellOrder ImportError: No module named model.order.SellOrder 

Is there anything I missed?

like image 601
user962206 Avatar asked May 15 '16 00:05

user962206


People also ask

How do I fix a Python module not found?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

Why am I getting module not found error?

A module not found error can occur for many different reasons: The module you're trying to import is not installed in your dependencies. The module you're trying to import is in a different directory. The module you're trying to import has a different casing.

How do I install a Python module?

The best and recommended way to install Python modules is to use pip, the Python package manager. Otherwise: Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py.


1 Answers

All modules in Python have to have a certain directory structure. You can find details here.

Create an empty file called __init__.py under the model directory, such that your directory structure would look something like that:

. └── project     └── src         ├── hello-world.py         └── model             ├── __init__.py             └── order.py 

Also in your hello-world.py file change the import statement to the following:

from model.order import SellOrder 

That should fix it

P.S.: If you are placing your model directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path.

like image 77
RafazZ Avatar answered Sep 25 '22 20:09

RafazZ