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?

+3


source to share


3 answers


Add the path to the lib folder to your SYS PATH environment variable. Then it can be imported from anywhere



import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)
import mymodule

      

+5


source


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.

+5


source


You need to use sys.path.append ("path"). But only use this once. Then try importing "my_module". THIS should be good. If you want to remove the added path, you can use sys.path.remove ("path").

0


source







All Articles