import python module given full path

How to Import Python Module Given Full Path

Sometimes you may need to import python module using the full path to a python file. In this article, we will learn how to import python module given full path.


How to Import Python Module Given Full Path

Here are the steps to import python module using full path to python file, in different versions of python. Replace module.name with the name of the module that you want to import from python file. And replace /path/to/file.py with the full path to python file which contains code for the required module.

Python 3.5+

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

Python 3.3 and 3.4

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

In python 3.3+, we use importlib function to import a library while in older versions we use imp module for the same purpose.

Python 2+

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

In this short article, we have learnt how to import module from python file. Once you have imported the module, you can use it like any other module that you import in your python script.

Also read:

How to Automate Backup in Python
How to Check Long Running Process in Linux
How to Backup & Restore Hard Disk in Linux
How to Lock & Unlock Users in Linux
How to Change FTP Port in Linux

Leave a Reply

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