I'm having trouble importing a module from a subfolder. No matter how many ways I try, I can't get it. This is my file structure:
ml-price-updater
├── main.py
├── publications
├── initiate_internal_data.py
├── models
│ ├── __init__.py
│ ├── models.py
│
│
├── mysql
│ ├── __init__.py
│ ├── mysql_commands.py
│ ├── mysql_services.py
│ ├── proof.py
From the "proof.py" file, which was generated for testing, I try to import the "Users" class from the "models" file in the "models" folder. When doing so, I get this error:
Traceback (most recent call last):
File "/home/valen/Escritorio/projects/ml-price-updater/publications/mysql/proof.py", line 1, in <module>
from publications.models.models import Users
ModuleNotFoundError: No module named 'publications'
The models.py file:
import uuid
class Users():
def __init__(self, email, password, uid = None):
self.email = email
self.password = password
self.uid = uid or uuid.uuid4()
def to_dict(self):
return vars(self)
The proof.py file:
from publications.models import models
user = Users('[email protected]', 'password123')
print(user.to_dict())
I would try to create an init .py file inside the publications folder and import User from proofs.py with from models.models import User
One way around this is to use
sys.path.append("..")
, which adds the specified path to the list of paths where python looks for modules to import.Once added, you can go into the folder
models
and import the classUsers
from themodels.py
. To do this, typefrom models.models import Users
.Otherwise, it can be executed
sys.path.append('../..')
that will add a "deeper" path and thus be able to import in a clearer way, like this:from publications.models.models import Users
More information