python - 如何从 Python 3 中的当前目录中的文件导入?

标签 python python-3.x python-3.4

在 python 2 中,我可以创建这样的模块:

parent
->module
  ->__init__.py (init calls 'from file import ClassName')
    file.py
    ->class ClassName(obj)

这行得通。在 python 3 中,我可以从命令解释器做同样的事情并且它有效(编辑:这有效,因为我在运行解释器的同一目录中)。但是,如果我创建 __ init __.py 并像这样执行相同的操作:

"""__init__.py"""
from file import ClassName

"""file.py"""
class ClassName(object): ...etc etc

我收到 ImportError: cannot import name 'ClassName', 它根本看不到 'file'。它会在我导入模块后立即执行此操作,即使我可以通过直接引用它来导入所有内容(我不想这样做,因为它与我们的代码库的其余部分完全不一致)。给了什么?

最佳答案

在 python 3 中,所有导入都是绝对的,除非给出相对路径来执行导入。您将需要使用绝对导入或相对导入。

绝对导入:

from parent.file import ClassName

相对导入:

from . file import ClassName
# look for the module file in same directory as the current module

关于python - 如何从 Python 3 中的当前目录中的文件导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269437/

相关文章:

python - 使用 python 脚本下载文件时出现错误

python - 是否可以在 python 中过滤测试文件和具有不同模式的单独测试?

python-3.x - pyinstaller 可执行文件失败

python - pip 安装到错误的文件夹,即使 `which pip` 是正确的

Python 使用 pandas 将 xlsx 转换为 csv 文件。如何删除索引列?

Python 请求在尝试使用数据 POST 时出现 TypeError

python - 如何在 Python 上安装 PyGame?

linux - 如何将带有国家字符的Linux Python 3.4代码转换成windows中的可执行代码

python - 如何将 Telegram 聊天机器人中的内联键盘设置为 python-telegram-bot 中的其他功能?

python - IntegrityError : (1048, "Column ' username' cannot be null") when emailid is also unique key