Python可以';找不到导入到另一个模块中的模块
我的项目结构如下:Python可以';找不到导入到另一个模块中的模块,python,python-3.x,python-module,Python,Python 3.x,Python Module,我的项目结构如下: │ main.py │ ├───equations │ resolving.py │ resolving_methods.py │ __init__.py │ └───func │ converter.py │ __init__.py │ └───templates func_template.py 我试图从func.converter导入main.py类,并从equat
│ main.py
│
├───equations
│ resolving.py
│ resolving_methods.py
│ __init__.py
│
└───func
│ converter.py
│ __init__.py
│
└───templates
func_template.py
我试图从func.converter导入main.py类,并从equations.resolving\u方法导入所有类
from func.converter import func_converter
from equations.resolving_methods import *
在这些文件(转换器和解析方法)中,我有以下几行代码:
/转换器.py
with open('templates/new_func.py', 'w', encoding='utf-8') as new_f:
from templates.new_func import my_func
/解决方法:
from resolving import resolving
和python给出以下错误:
ImportError: No module named 'resolving'
但是,当我尝试单独运行这些文件时,代码不会出现任何错误您使用的是绝对导入。绝对导入仅查找顶级模块,而您正在尝试导入嵌套在包中的名称 您需要指定完整的包路径,或者使用包相对引用,使用
:
# absolute reference with package
from equations.resolving import resolving
# package relative import
from .resolving import resolving
请参见Python教程的第二部分
您的converter.py
模块还有一个问题,即尝试打开具有相对路径的文件。路径'templates/new_func.py'
将根据当前工作目录解析,该目录可能位于计算机上的任何位置。根据模块\uuuu文件\uuuuu
参数使用绝对路径:
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: