Can I import a file without file extension .py?

J

Jia Lu

Hi all
I wonder if I can import a file with other file extensions ?

Can I do that only with python?

Thank you

Jia Lu
 
B

Ben Finney

Jia Lu said:
I wonder if I can import a file with other file extensions ?

I use this function in most of my test infrastructures, to import
programs as modules for unit testing.

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__

return module
 
J

Jia Lu

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__

Thank you very much.
And can you tell me what does " exec module_file in module.__dict__ "
mean?

Thanx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top