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 25, 2020 in Python by Rajiv
• 8,870 points
2,563 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,770 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 15, 2020 1,653 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
926 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,469 views
0 votes
1 answer
+5 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,790 points
4,128 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 25, 2020 in Python by Gitika
• 65,770 points
1,037 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,770 points
956 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP