Python 不会导入同一目录中的文件

问题描述 投票:0回答:1

所以我的目录看起来像这样:bleh

文件

CreatePage.py
包含导入语句
from Page import *
但运行时会抛出以下错误

No module named 'Page'
  File "D:\My Stuff\School\CS\ViewModel\CreatePage.py", line 1, in <module>
    from Page import *
  File "D:\My Stuff\School\CS\View.py", line 2, in <module>
    from ViewModel.CreatePage import *
ModuleNotFoundError: No module named 'Page'

我也尝试了

import Page
from ViewModel.Page import *
,但它们也不起作用。

我在这里做错了什么?

python import module python-import
1个回答
0
投票

我可以重现类似的东西

查看.py

from ViewModel.CreatePage import *

ViewModel/CreatePage.py

from Page import *

ViewModel/Page.py

print("Page")

运行方式:

python3 View.py

Traceback (most recent call last):
  File "/home/td/tmp/a/test/View.py", line 1, in <module>
    from ViewModel.CreatePage import *
  File "/home/td/tmp/a/test/ViewModel/CreatePage.py", line 1, in <module>
    from Page import *
ModuleNotFoundError: No module named 'Page'

通过将 ViewModel/CreatePage.py 更改为相对导入来解决这个问题

from .Page import *

再次奔跑

Page
© www.soinside.com 2019 - 2024. All rights reserved.