Importing a module from a specific folder
I have a folder named Script
and inside I have a temp.py
script. My temp script is importing a module from a subfolder named lib
.
Lib folder has empty __init__.py
and my parent_computer_test.py
script.
I temp.py
have the following code in my script:
import lib.parent_computer_test as parent_computer_test
parent_computer_test.mainChunk()
parent_computer_test.splitChunks()
I was able to import a module from a subfolder without any big problems.
This workflow / script works fine, BUT for a specific reason, my folder lib
must be somewhere else on my computer. There is a long story as to why, but it must be so.
Shortly speaking. I want mine temp.py
from folder to /Script
import modules from folder lib
(or whatever name) using parent_computer_test.py
, but at the same time this folder is not a subfolder /Script
- so it is somewhere else in the computer. It could be C:/development/...
or something else.
So my question is how to import a module from a specific folder?
source to share
import imp
yourModule = imp.load_source('yourModuleName', '/path/to/yourModule.py')
foo = yourModule.YourFunction("You", "get", "the", "idea.")
I realize this is a special case, but in general I would avoid such things. Things can get ugly when you use absolute paths, especially if you move things around, and I will only use them for ejection scenarios or on systems that won't change much.
EDIT: Aswin's answer is a much better long term solution.
source to share