[英]Python Importing files from other folders (within the same project) using __init__.py?
尝试从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.