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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31269437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:44:09  来源:igfitidea点击:

How do I import from a file in the current directory in Python 3?

pythonpython-3.xpython-3.4

提问by

In python 2 I can create a module like this:

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

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

And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:

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

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

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

I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?

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

回答by doru

Try import it this way:

尝试以这种方式导入:

from .file import ClassName

See heremore info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.

在此处查看有关在 python 3 中导入的“Guido 的决定”的更多信息以及有关如何在 python 3 中导入的完整示例。

回答by Dunes

In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.

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

Absolute import:

绝对导入:

from parent.file import ClassName

Relative import:

相对进口:

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