在Python中导入文件
我有该文件结构 -
Blog\DataObjects\User.py
Blog\index.py
我想导入该函数(say_hello) 来自index.py 的User.py。 我正在尝试这段代码 -
from Blog.DataObjects.User import say_hello
say_hello()
我有这个错误 -
Traceback (most recent call last):
File "index.py", line 1, in <module>
from Blog.DataObjects import User
ImportError: No module named Blog.DataObjects
I have that file structure-
Blog\DataObjects\User.py
Blog\index.py
I want to import the function(say_hello) at User.py from index.py.
I am trying this code -
from Blog.DataObjects.User import say_hello
say_hello()
And I have that error -
Traceback (most recent call last):
File "index.py", line 1, in <module>
from Blog.DataObjects import User
ImportError: No module named Blog.DataObjects
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 期望在每个可导入的目录中都有一个文件
__init__ .py
,它可能是空的。因此,如果您将文件结构更正为:如果目录的路径位于您的 Python 路径中,它应该可以工作(您可以使用以下命令进行检查
:)。如果没有,请注意导入是相对于当前文件的位置完成的。也就是说,由于 index.py 已经在
Blog
中,因此导入应为:Python expects in every directory that should be importable, a file
__init__.py
, which may be empty. So, if you correct your file structure to this:it should work, if the path to the directory is in your Python path (you can check this with:
). If not, mind that importing is done relative to the position of the current file. That is, since index.py is already inside
Blog
, the import should read: