import on modules/files that don't have .py extension

A

Anthony_Barker

Is it possible to import modules/files that have something other than
the .py extension?
 
P

Peter Hansen

Anthony_Barker said:
Is it possible to import modules/files that have something other than
the .py extension?

Something like this?

import os, imp

filepath = '/some/long/path/to/file.notpy'
f = open(filepath)
description = ('.notpy', 'r', imp.PY_SOURCE)
module = imp.load_module('__main__', f, filepath, description)

(Slightly edited from some working code.)

-Peter
 
D

David Boddie

Is it possible to import modules/files that have something other than
the .py extension?

You can use the imp module to achieve this. For example, for a module
called "mymodule" in a source file called "myfile" then

import imp
mymodule = imp.load_source("mymodule", "myfile")

should import the contents of "myfile" as a module which you can use
as normal. The "mymodule" parameter to the load_source function
presumably just ensures that

mymodule.__name__ = "mymodule"

so that anything relying on that has no nasty surprises. Note that, for this
example, you may end up with a file called "myfilec" alongside "myfile".

David
 

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,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top