How to import .py file from another directory?

Andrius picture Andrius · Apr 9, 2014 · Viewed 169.3k times · Source

I have this structure of files (directory and after arrow files):

model -> py_file.py 
report -> other_py_file.py

main __init__.py:

import model
import report

model directory:

import py_file

report directory:

import other_py_file

now in other_py_file I want to import py_file, but what ever I try I give error that there is no such module.

I tried this: from model import py_file

Then: import py_file

Looks like these two folders don't see each other. What is the way to import file from other directory? Do I need to specify some additional imports in init.py files?

Answer

anon582847382 picture anon582847382 · Apr 9, 2014

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.