How do I import a Python script from a sibling directory?

PythonImportPathPythonpath

Python Problem Overview


Let's say I have the following directory structure:

parent_dir/
    foo_dir/
        foo.py
    bar_dir/
        bar.py

If I wanted to import bar.py from within foo.py, how would I do that?

Python Solutions


Solution 1 - Python

If all occurring directories are Python packages, i.e. they all contain __init__.py, then you can use

from ..bar_dir import bar

If the directories aren't Python packages, you can do this by messing around with sys.path, but you shouldn't.

Solution 2 - Python

You can use the sys and os modules for generalized imports. In foo.py start with the lines

import sys
import os
sys.path.append(os.path.abspath('../bar_dir'))
import bar

Solution 3 - Python

Let's say if you have following structure:

root
  |_ productconst.py
  |_ products
     |_ __init__.py

And if you would like to import productconst in products.__init__, then following can be used :

from ..productconst import * 

Solution 4 - Python

If you're having issues in python 3+, the following worked for me using sys.path.append("..").

sys.path.append("..")
from bar_dir import bar

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrcrisView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonprraoView Answer on Stackoverflow
Solution 3 - PythonSukhmeet SethiView Answer on Stackoverflow
Solution 4 - PythonPeter GirnusView Answer on Stackoverflow