Home > Back-end >  How to import a file in python?
How to import a file in python?

Time:09-23

How to access models/usrs from resources/user

├───models
|   └───user.py
├───resources
|   └───user.py

First I import it like this one:

from code.models.user import UserModel

But I got a compile-time error:

`Cannot find reference 'models' in 'code.py'`

And I tried another way like this one:

from ..models.user import UserModel

But I got a runtime error:

ImportError: attempted relative import beyond top-level package

And I added init.py in both files but still doesn't work.

enter image description here

And also I tried these solutions but they don't fix my issue, please help me

CodePudding user response:

Add the models and resources directories to your $PYTHONPATH or use sys.path:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

Or:

import sys
sys.path.insert(0, "/home/project-name/models")

Or add "__ init__.py" to code directory:

from code.models import user

CodePudding user response:

And finally, I fix my issue:

As @Little Bamboo said: I used sys concept for the import like below:

import sys    
sys.path.append("D:\\Projects\\Python\\UdemyProjects\\SixSimplifyingTwo")    
from mycode.models.userone import UserModel

But that was not all, some of my files had the same names and I changed the names of the files.

And also I had a folder called code, and from the below link I understood that code is a built-in Python module and I changed the code folder name.

Werkzeug AttributeError: 'module' object has no attribute 'InteractiveInterpreter'

  • Related