如何从相对路径导入?

时间:2013-10-29 05:40:05

标签: python

我发布这个是因为这个问题(Import a module from a relative path)的答案对于我们这些可能首先提出问题的人来说是不可用的。

假设我有以下文件结构(我保留了与其他问题相同的命名约定):

C:\dirMain\
     dirFoo\
        Foo.py
     dirBar\
        Bar.py

我想从Bar.py内导入Foo.py

这样的事情:(我的C在这里显示,对不起):

# Foo.py
from ../dirBar/Bar import *

请随意标记为副本,但请先检查其他回复;我见过的大多数都过于复杂,不起作用或者不完整。这是一个简单的问题,希望有一个简单的答案。

我尝试过的事情:

1)Puffin GDI的建议如下:

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

结果:

  

NameError:未定义名称“文件

对此的解决方案表面上位于this answer中,我不知道。

2)从这里开始:How to import a module given the full path?

import imp
abc = imp.load_source('bar.py', 'C:\dirMain\dirBar.py')

结果:

  

IOError:[Errno 22]参数无效

3)如下所述:Import a module from a relative path

(首先将__init__.py添加到/dirBar

from ..dirBar import Bar

结果:

  

ValueError:在非包中尝试相对导入

1 个答案:

答案 0 :(得分:0)

在所有程序中导入根路径。在所有程序中从根开始旅行路径。

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

root = "C:\dirMain"
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), root)))

您可以在配置中编写根路径,然后

from dirBar.Bar import class_name
相关问题