python从相对路径导入

时间:2017-01-26 15:53:40

标签: python-2.7 import io path

关于设置相对路径导入的问题。我有一堆文件(模块) “/用户/ MYNAME /桌面/ programX_files / programX /普通/ 如:

  1. /Users/myname/Desktop/programX_files/programX/common/constants.py
  2. /Users/myname/Desktop/programX_files/programX/common/util/misc.py
  3. 每个模块都有一行来根据需要从common /目录中导入其他模块。例子:

    (/Users/myname/Desktop/programX_files/programX/common/constants.py)中的“constants.py”包含以下行:

    • 将programX.common.util.misc导入为util_misc

    (/Users/myname/Desktop/programX_files/programX/common/util/misc.py)中的“misc.py”包含以下行:

    • 将programX.common.constants导入为常量

    现在我想使用这些模块。我如何正确地让python知道如何设置正确的路径依赖关系以便它能够查看(/ Users / myname / Desktop / programX_files / programX / common /)以及常见的子目录?

    我尝试添加路径,但它不起作用:

    >>> import sys
    >>> sys.path.append('/Users/myname/Desktop/programX_files/programX/')
    >>> import programX.common.constants.py as constants
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named programX.common.constants.py
    >>> 
    >>> sys.path.append('/Users/myname/Desktop/programX_files/programX/common/')
    >>> sys.path.append('/Users/myname/Desktop/programX_files/programX/common/util')
    >>> 
    >>> import programX.common.constants.py as constants
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named programX.common.constants.py
    >>> 
    >>> import os
    >>> os.getcwd()
    '/Users/myname'
    >>> 
    >>> import Desktop.programX_files.programX.common.constants.py as constants
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named Desktop.programX_files.programX.common.constants.py
    >>> 
    

    我猜这可能是一个相对简单的解决方案,但我无法弄清楚。谢谢你的回答。

1 个答案:

答案 0 :(得分:0)

您的代码应如下所示:

import sys
# set path to folder
sys.path.append('/Users/myname/Desktop/programX_files/')
# now import files
import programX.common.constants.py as constants