Python 使用 __init__.py 从其他文件夹(同一项目内)导入文件?

标签 python import directory

尝试从 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/

相关文章:

python - 创建一个函数来计算不同年份的中位数成本

python - "Requested entity was not found."当管理员尝试修补另一个用户签名时

mysql - 从 csv 导入 mysql 的日期为 0000-00-00

linux - xquery 无法加载 http ://expath. org/ns/http-client

java - Android/Java - 带条件的递归扫描

python - 如何在不多次调用函数的情况下访问函数内、函数外生成的字典。 PYTHON

python - 将 PyQt3D 窗口集成到 QMainWindow

python - 如何在 Anaconda(Jupyter 笔记本)中导入 python 自定义类

javascript - 列出 Web 应用程序上的本地目录

unix - GNU 找到 : Search in current directory first