Python - module not found

I am starting with Python. Before you begin, here is my Python folder structure

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

In src , I have a folder called model that has a Python file called order.py whose contents are as follows:

 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 , this results in an 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 something I missed?

+17
python module
source share
3 answers

All modules in Python must have a specific directory structure. Here you can find the details.

Create an empty file named __init__.py in the model directory so that your directory structure looks something like this:

 . └── project └── src β”œβ”€β”€ hello-world.py └── model β”œβ”€β”€ __init__.py └── order.py 

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

 from model.order import SellOrder 

That should fix it :)

PS: If you place your model directory in a different place (not in the same directory branch), you will have to change the python path using sys.path .

+15
source share

you need a file named __init__.py (two underscores on each side) in each folder in the hierarchy, so one in src/ and one in model/ . This is what python is looking to know that it needs to access a specific folder. Files should contain initialization instructions, but even if you create them empty, this will solve it.

+2
source share

You must make sure the module is installed for all versions of python

You can check if the module is installed for python by running:

pip uninstall moduleName

If it is installed, it will ask you if you want to remove it or not. My problem was that it was installed for python, but not for python3. To check if a module is installed for python3, run:

python3 -m pip uninstall moduleName

After that, if you find that the module is not installed for one or both versions, use these two commands to install the module.

  • pip install moduleName
  • python3 -m pip install moduleName
0
source share

All Articles