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?
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 .
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With