如何在父目录中导入一个 Python 文件

3
如果我有以下目录结构:
parent/
    - __init__.py
    - file1.py
    - child/
        - __init__.py
        - file2.py

在文件2中,我应该如何导入文件1?
更新:
>>> import sys
>>> sys.path.append(sys.path.append('/'.join(os.getcwd().split('/')[:-2])))
>>> import parent
>>> ImportError: No module named parent
4个回答

8

你需要指定父级并且它需要在sys.path中。

import sys
sys.path.append(path_to_parent)
import parent.file1

我尝试了这个[请参见上面修改后的问题],但似乎仍然遇到了同样的问题。 - David542
你的树形结构里有错别字,你需要使用__init__.py而不是__.init__.py - Intra
3
在这种情况下,不应使用sys.path hacks。普通的绝对/相对导入就足够了。 - jfs

5

你仍然需要提及父级,因为它们位于不同的命名空间中:

import parent.file1

2
即使我提到了父级,我仍然会得到相同的导入错误。 - David542
@David542 显然,父目录需要出现在sys.path中。 - Jiri
@Jiri,我尝试了这个[请参见上面修改后的问题],但似乎仍然遇到了同样的问题。 - David542
@David542 尝试使用 sys.path.append('/Users/Premiere_032/Desktop') 代替。 - Jacob
@JacobAbrahams 很遗憾,结果相同。 - David542
2
@David542,你给__init__.py文件命名错误了。它的结尾不应该有下划线!正确的命名方式是:init.py。 - Jiri

0

-1

这是我制作的一个可以导入任何东西的工具。当然,你仍然需要将此脚本复制到本地目录中,进行导入,并使用你想要的路径。

import sys
import os

# a function that can be used to import a python module from anywhere - even parent directories
def use(path):
    scriptDirectory = os.path.dirname(sys.argv[0])  # this is necessary to allow drag and drop (over the script) to work
    importPath = os.path.dirname(path)
    importModule = os.path.basename(path)
    sys.path.append(scriptDirectory+"\\"+importPath)        # Effing mess you have to go through to get python to import from a parent directory

    module = __import__(importModule)
    for attr in dir(module):
        if not attr.startswith('_'):
            __builtins__[attr] = getattr(module, attr)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接