【问题标题】:Python ModuleNotFoundError: No module named '<directory>''Python ModuleNotFoundError:没有名为“<目录>”的模块
【发布时间】:2021-04-08 11:05:11
【问题描述】:

我想从 subdir 导入一个文件,我收到这样的错误:

ModuleNotFoundError: 没有名为“特殊”的模块

│   
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── special
    ├── __init__.py
    └── wantToImport.py =================>>>I want to import this file

我的 case.py 是这样的:

from special.wantToImport import ImportClass

我的 wantToImport.py 文件是这样的:

class ImportClass:

    def mydefination(self):
        #Some codes here
 

我想在我的 case.py 文件上使用 mydefinitioon 函数但是我无法导入这个文件。 为什么我收到此错误? 我该如何解决这个问题?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你应该告诉 Python 你的模块路径在当前目录中(使用.):

from .special.wantToImport import ImportClass

【讨论】:

    【解决方案2】:

    尝试在您正在工作的目录中创建一个__init__.py 文件,并使用它来引用您的模块。

    │
    root   
    ├── constants.py
    ├── crawler.py
    ├── case.py ===================>>>> I working on this file
    ├── __init__.py
    ├── special
        ├── __init__.py
        └── wantToImport.py =================>>>I want to import this file
    

    使用导入它

    from root.special.wantToImport import ImportClass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 2021-03-09
      • 2021-06-03
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多