Python – Load Module from File (by Filename)


You know where a file is and want to load it as a module.

This loads from the file test1 from the directory in which this file is located too.


import os
import imp
def myimp(name):
thisdir = os.path.dirname( myimp.func_code.co_filename )
filename = os.path.join(thisdir, name + ".py")
fp = file(filename, "r")
description = (".py", "r", imp.PY_SOURCE)
return imp.load_module(name, fp, thisdir, description)
test1 = myimp("test1")

  1. No comments yet.
(will not be published)

  1. No trackbacks yet.