Skip to content Skip to sidebar Skip to footer

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? U

Solution 1:

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

Solution 2:

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

import parent.file1

Solution 3:

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)

Solution 4:

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 directoriesdefuse(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 indir(module):
        ifnot attr.startswith('_'):
            __builtins__[attr] = getattr(module, attr)

Post a Comment for "How To Import A Python File In A Parent Directory"