从依赖于另一个文件的其他目录中的文件导入 python 函数
importing a python function from a file in other directory which depends on another file
这是我的目录结构
-directory1
|-currentlyWritingCode
-directory2
|-__init__.py
|-helper.py
|-view.ui
helper.py 是来自 pyqt4 框架的 UI。它需要 view.ui 文件。
它有以下代码来加载 ui 数据
viewBase, viewForm = uic.loadUiType("view.ui")
现在在当前编写的代码中的 directory1 中我这样做了
import directory2.helper
当我 运行 currentlyWritingCode 中的代码时,它抛出一个错误
FileNotFoundError: [Errno 2] No such file or directory: 'view.ui'
现在怎么办?
在 Centos 7 上使用来自 anaconda 的 python3.5
使用 os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui')
代替 view.ui
。这将确保您正确引用 python 文件所在的文件夹,而不管导入它的代码如何。
注意:确保您有 import os
和其他导入。
这是如何工作的?
__file__
是您正在导入的模块的属性。它包含模块文件的路径。如果有,请参见 this answer. However, this path is not necessarily an absolute path. os.path.realpath
returns the absolute path (it even follows symlinks)。此时我们有了模块的完整路径,所以我们采用目录路径 (os.path.dirname
) 并将其与原始文件名(我们假设它是相对于原始模块的,因此应该在上述目录)。 os.path.join
确保在构建文件路径时使用正确的 \
或 /
,以便代码在任何平台上都能正常工作。
这是我的目录结构
-directory1
|-currentlyWritingCode
-directory2
|-__init__.py
|-helper.py
|-view.ui
helper.py 是来自 pyqt4 框架的 UI。它需要 view.ui 文件。 它有以下代码来加载 ui 数据
viewBase, viewForm = uic.loadUiType("view.ui")
现在在当前编写的代码中的 directory1 中我这样做了
import directory2.helper
当我 运行 currentlyWritingCode 中的代码时,它抛出一个错误
FileNotFoundError: [Errno 2] No such file or directory: 'view.ui'
现在怎么办?
在 Centos 7 上使用来自 anaconda 的 python3.5
使用 os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui')
代替 view.ui
。这将确保您正确引用 python 文件所在的文件夹,而不管导入它的代码如何。
注意:确保您有 import os
和其他导入。
这是如何工作的?
__file__
是您正在导入的模块的属性。它包含模块文件的路径。如果有,请参见 this answer. However, this path is not necessarily an absolute path. os.path.realpath
returns the absolute path (it even follows symlinks)。此时我们有了模块的完整路径,所以我们采用目录路径 (os.path.dirname
) 并将其与原始文件名(我们假设它是相对于原始模块的,因此应该在上述目录)。 os.path.join
确保在构建文件路径时使用正确的 \
或 /
,以便代码在任何平台上都能正常工作。