python3: 在 python 文件中导入另一个函数:没有名为 load 的模块

python3: import another function in python file: No module named load

在 PyCharm 编辑器中,我有一个名为 project3 的 python 应用程序,其目录结构如下。文件load.py只是有一个函数(不是classpy文件)def read():mip.py是一个pyclass文件,并且有自己的函数方法。

 Project
  |
  +---- project1
  |
  +---- project2
  |
  +---- project3
          |
          +---- cnn.py
          +---- load.py
          +---- mip.py

cnn.py中,我想导入我打算使用的loadmip文件。我的导入代码如下;

import load
from mip import f1

但是我得到错误:

No module named load
Unresolved reference 'mip'

得到了回答,由于我对 PyCharm 没有太多经验,我将避免在 IDE 中对您应该如何处理它发表评论。

相反,我会向您推荐 the package docs:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

最简单的解决方案是在同一目录中添加一个名为 __init__.py 的空白文件:

In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

在 IDE 中,您只需在项目中创建一个新文件,将其命名为 __init__.py 并保存,然后重新启动 PyCharm 即可。

如果你想用 python 模块和包做(或只是阅读)更复杂的事情,你可以看到 distutils.

在 pycharm 中,您必须添加 project3(以及任何其他包含模块的目录)作为包含源的根目录。

右键单击您的 project3 目录,然后在上下文菜单中 select:将目录标记为 > Sources Root

我有类似的问题,我在目录中添加了 init.py 文件,现在它工作正常。

  1. 转到其他目录中需要导入文件的目录。
  2. 创建一个新的 python 名称为 init.py 的新文件或从现有项目复制并粘贴到同一目录
  3. 将同一目录class或python文件导入其他目录或同一目录中不同的class或python文件