【问题标题】:Python Importing files from other folders (within the same project) using __init__.py?Python 使用 __init__.py 从其他文件夹(在同一个项目中)导入文件?
【发布时间】:2019-06-26 15:00:45
【问题描述】:

尝试从 bSubFile.py 中导入 aFile.py 但收到错误消息“exceptions.ValueError, Attempted relative import in non-package”

我的文件结构如下:

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():
...

但我总是得到“尝试在非包中进行相对导入”,我一定遗漏了一些非常明显的东西。谢谢!

【问题讨论】:

  • 看看importlib
  • 试试from app.FolderA import aFile
  • from app.folderA import aFile 只是给我一个错误“没有名为 app.FolderA 的模块”@drum
  • 也将其添加到 FolderA/__init__.py 中
  • 忘了问,aFile 是方法还是类?还是只是文件名?

标签: python import directory


【解决方案1】:

您可以将其他路径添加到您的系统路径。这可能不是最优雅的方式,但它确实有效。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多