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

Orcris picture Orcris · Apr 23, 2012 · Viewed 38.1k times · Source

Here is the directory structure:

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

How do I import bar.py into foo.py?

Answer

Sven Marnach picture Sven Marnach · Apr 23, 2012

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.