Explore Courses Blog Tutorials Interview Questions
0 votes
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("", "/path/to/") 

foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) 


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

from importlib.machinery import SourceFileLoader 

foo = SourceFileLoader("", "/path/to/").load_module() 


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

import imp 

foo = imp.load_source('', '/path/to/') 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
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories