How to import a module given the full path

0 votes
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.
Nov 24, 2020 in Python by Rajiv
• 8,880 points
129 views

1 answer to this question.

0 votes

For Python 3.5+ use:

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:

from importlib.machinery import SourceFileLoader

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

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
answered Nov 25, 2020 by Gitika
• 65,870 points

Related Questions In Python

0 votes
2 answers

How to Import a module from a relative path?

If i understand your question correct then ...READ MORE

answered Dec 14, 2020 in Python by Tanja84DK

edited Dec 14, 2020 88 views
0 votes
1 answer
+2 votes
1 answer

How to check the state of a user given instance id using filters

Seems like the "ec2_con_re.instances" you are using ...READ MORE

answered Aug 1, 2019 in Python by Aishwarya
211 views
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,032 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,555 views
0 votes
1 answer

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty ...READ MORE

answered Nov 24, 2020 in Python by Gitika
• 65,870 points
90 views
0 votes
1 answer

How to a write reg expression that confirms an email id using the python reg expression module “re”?

Hey, @Roshni, Python has a regular expression module ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,870 points
155 views