尝试从 bSubFile.py 中导入 aFile.py,但收到错误消息“exceptions.ValueError,尝试在非包中进行相对导入”
我的文件结构如下:
app/
- __init__.py
FolderA/
- __init__.py
- aFile.py
FolderB/
- __init__.py
- bFile.py
SubfolderB/
- __init__.py
- bSubFile.py
我正在尝试从 bSubFile.py 导入 aFile
尝试过:
from ..FolderA import aFile
class bSubFile():
...
和:
from ...FolderA import aFile
class bSubFile():
...
但我总是得到“尝试在非包中进行相对导入”,我一定错过了一些非常明显的东西。谢谢!
最佳答案
您可以将其他路径添加到系统路径中。这可能不是最优雅的方式,但它确实有效。
import sys
import os
# get the folder of the current file, go one directory back and add "FolderA"
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "FolderA"))
# now you can import everything that is in FolderA directly
import aFile
关于Python 使用 __init__.py 从其他文件夹(同一项目内)导入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489576/