Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import .py file from another directory? [duplicate]

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?

like image 589
Andrius Avatar asked Apr 09 '14 07:04

Andrius


People also ask

Does Python import twice?

What happens if a module is imported twice? The module is only loaded the first time the import statement is executed and there is no performance loss by importing it again. You can examine sys. modules to find out which modules have already been loaded.

Can import Python file from same directory?

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.


2 Answers

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.

like image 86
anon582847382 Avatar answered Sep 19 '22 19:09

anon582847382


Python3:

import importlib.machinery  loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py') handle = loader.load_module('report')  handle.mainFunction(parameter) 

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib module = importlib.load_module('folder.filename') module.function() 

Kudos to Sebastian for spplying a similar answer for Python2:

import imp  foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() 
like image 24
Torxed Avatar answered Sep 17 '22 19:09

Torxed