How to import a python file in a parent directory

2019-07-19 21:33发布

If I have the following directory structure:

parent/
    - __init__.py
    - file1.py
    - child/
        - __init__.py
        - file2.py

In file 2, how would I import file 1?

Update:

>>> import sys
>>> sys.path.append(sys.path.append('/'.join(os.getcwd().split('/')[:-2])))
>>> import parent
>>> ImportError: No module named parent

标签: python
4条回答
Viruses.
2楼-- · 2019-07-19 21:34

Here's something I made to import anything. Of course, you have to still copy this script around to local directories, import it, and use the path you want.

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)
查看更多
等我变得足够好
3楼-- · 2019-07-19 21:38

You need to specify parent and it needs to be on the sys.path

import sys
sys.path.append(path_to_parent)
import parent.file1
查看更多
虎瘦雄心在
4楼-- · 2019-07-19 21:42

There is a whole section about Modules on the Python Docs:

Python 2: http://docs.python.org/tutorial/modules.html

Python 3: http://docs.python.org/py3k/tutorial/modules.html

In both see section 6.4.2 for specific imports of parent packages (and others too)

查看更多
【Aperson】
5楼-- · 2019-07-19 21:47

You still need to mention the parent, since they're in different namespaces:

import parent.file1
查看更多
登录 后发表回答