python – How to import a module given the full path?

python – How to import a module given the full path?

For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location(, /path/to/
foo = importlib.util.module_from_spec(spec)

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader(, /path/to/

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

import imp

foo = imp.load_source(, /path/to/

There are equivalent convenience functions for compiled Python files and DLLs.

See also

The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:

import sys
# the mock-0.3.1 dir contains, &

from testcase import TestCase
from testutils import RunTests
from mock import Mock, sentinel, patch

python – How to import a module given the full path?

To import your module, you need to add its directory to the environment variable, either temporarily or permanently.


import sys
import my_module


Adding the following line to your .bashrc (or alternative) file in Linux
and excecute source ~/.bashrc (or alternative) in the terminal:

export PYTHONPATH=${PYTHONPATH}:/path/to/my/modules/

Credit/Source: saarrrr, another Stack Exchange question

Leave a Reply

Your email address will not be published. Required fields are marked *