David542
David542

Reputation: 110472

How to import a python file in a parent directory

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

Upvotes: 3

Views: 13108

Answers (4)

B T
B T

Reputation: 60985

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)

Upvotes: -1

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)

Upvotes: 0

Intra
Intra

Reputation: 2109

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

Upvotes: 8

Jacob
Jacob

Reputation: 995

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

import parent.file1

Upvotes: 5

Related Questions