[英]Importing from sibling directory
I have searched this question over stackoverflow but can't find an answer that fixes this.我已经在 stackoverflow 上搜索了这个问题,但找不到解决这个问题的答案。 I am trying to learn how to do proper imports with python.
我正在尝试学习如何使用 python 进行正确的导入。
I am using Python 3.8.2 and I have the following simple directory setup.我正在使用 Python 3.8.2 并且我有以下简单的目录设置。
main_folder\
folder1\
myclass.py
folder2\
testclass2.py
testclass1.py
Both testclass1.py and testclass2.py have this inside: testclass1.py 和 testclass2.py 里面都有这个:
from folder1.myclass import Myclass
This works fine for testclass1.py, but when I run in testclass2.py it gives me an error.这适用于 testclass1.py,但是当我在 testclass2.py 中运行时,它给了我一个错误。
ModuleNotFoundError: No module named 'folder1'
ModuleNotFoundError: 没有名为“folder1”的模块
Even though I had read Python no longer requires this, I inserted an __init__.py
file into folder1.即使我读过 Python 不再需要这个,我还是在 folder1 中插入了一个
__init__.py
文件。 This generated the same error.这产生了同样的错误。 I then tried following directions for the init file in this article but there was no improvement.
然后我尝试按照本文中init 文件的说明进行操作,但没有任何改进。 I also tried using relative paths versus absolute paths for import, but no success.
我也尝试使用相对路径与绝对路径进行导入,但没有成功。
Help is much appreciated.非常感谢帮助。
从testclass2.py
导入应该是这样的:
from ..folder1.myclass import Myclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.