如何导入给定相对路径的Python模块?

例如,如果dirFoo包含Foo.py和dirBar,而dirBar包含Bar.py,我如何将Bar.py导入Foo.py?

下面是一个视觉表示:

dirFoo\
    Foo.py
    dirBar\
        Bar.py

Foo希望包含Bar,但重组文件夹层次结构不是一个选项。


当前回答

相对sys.path示例:

# /lib/my_module.py
# /src/test.py


if __name__ == '__main__' and __package__ is None:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module

基于这个答案。

其他回答

import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

以下是使用相对路径从上面的一个级别导入文件的方法。

基本上,只需将工作目录向上移动一个级别(或任何相对位置),将其添加到路径中,然后将工作目录移回其起始位置。

#to import from one level above:
cwd = os.getcwd()
os.chdir("..")
below_path =  os.getcwd()
sys.path.append(below_path)
os.chdir(cwd)

确保dirBar具有__init__.py文件——这会将一个目录放入Python包中。

在我看来,最好的选择是将__init__.py放在文件夹中,并使用

from dirBar.Bar import *

不建议使用sys.path.append(),因为如果使用与现有python包相同的文件名,可能会出现问题。我还没有测试过,但这将是模棱两可的。

添加__init__.py文件:

dirFoo\
    Foo.py
    dirBar\
        __init__.py
        Bar.py

然后将以下代码添加到Foo.py的开头:

import sys
sys.path.append('dirBar')
import Bar