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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Anthony_Barker

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

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

    #2
    Re: import on modules/files that don't have .py extension

    Anthony_Barker wrote:[color=blue]
    >
    > Is it possible to import modules/files that have something other than
    > the .py extension?[/color]

    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

    Comment

    • David Boddie

      #3
      Re: import on modules/files that don't have .py extension

      anthony_barker@ hotmail.com (Anthony_Barker ) wrote in message news:<899f842.0 309170649.517e0 bb9@posting.goo gle.com>...[color=blue]
      > Is it possible to import modules/files that have something other than
      > the .py extension?[/color]

      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

      Comment

      Working...