I have a project structure like this:
│ main.py
│
├───equations
│ resolving.py
│ resolving_methods.py
│ __init__.py
│
└───func
│ converter.py
│ __init__.py
│
└───templates
func_template.py
I'm tried to import to main.py class from func.converter and all classes from equations.resolving_methods
from func.converter import func_converter
from equations.resolving_methods import *
In this files (converter and resolving_methods) I have this lines of code:
/converter.py
with open('templates/new_func.py', 'w', encoding='utf-8') as new_f:
from templates.new_func import my_func
/resolving_methods:
from resolving import resolving
And python give following error:
ImportError: No module named 'resolving'
But, when I try to run this files separately, code works without any errors
You are using absolute imports. Absolute imports only find top-level modules , while you are trying to import names that are nested inside packages.
You'll either need to specify the full package path, or use a package-relative reference, using .
:
# absolute reference with package
from equations.resolving import resolving
# package relative import
from .resolving import resolving
See the Intra-package References section of the Python tutorial.
Your converter.py
module has the additional issue of trying to open a file with a relative path. The path 'templates/new_func.py'
will be resolved against whatever the current working directory is going to be, which could be anywhere on the computer. Use absolute paths, based on the module __file__
parameter:
import os.path
HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(HERE, 'new_func.py'), 'w', encoding='utf-8') as new_f:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.