【问题标题】:How to import from another folder (python)如何从另一个文件夹导入(python)
【发布时间】:2013-06-03 01:50:50
【问题描述】:

我从文件夹 A 运行(名字无关紧要),在这个文件夹中还有另一个文件夹叫 bin。

在 bin 中我有 .py 文件“functions”,如果我在文件夹 A 中,如何导入它。

提醒:main.py -> 位置:A

提醒:functions.py -> 位置:A/bin

谢谢。

【问题讨论】:

  • from bin.functions import function1, function2 要做到这一点,请确保bin/ 有一个__init__.py
  • 是的.. 一个名为__init__.py的空文件

标签: python import directory


【解决方案1】:

您需要创建一个空文件bin/__init__.py。这将告诉 python bin 是一个“包”,应该在那里寻找模块。

from bin import functions

如果你想做类似from bin.functions import * 的事情,你可以在__init__.py 中添加你想加载的函数(更多here

# __init__.py
__all__ = ["fun1", "fun2"]
# doing import * will load those 2

您可以找到更多信息here

【讨论】:

  • 谢谢,这很有帮助
  • 另一个小问题,如果我想导入所有函数(例如:from hi import *)?
猜你喜欢
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2020-01-24
  • 1970-01-01
相关资源
最近更新 更多