Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.

1 Answer

0 votes
by (106k points)

 

To load the file in Python 3.5 you can run the following code:-

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()

For Python 3.3 and 3.4 use the following piece of code:-

from importlib.machinery import SourceFileLoader 

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

foo.MyClass()

If you are Python 2 user you can run the following code:-:

import imp 

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 1, 2019 in Python by Sammy (47.6k points)
+2 votes
3 answers

Browse Categories

...