I have a Python source code file called foobar
. It has no .py
extension because I also use it as a standalone script, and I don't want to type the .py
extension to run it. In the same directory I have another python file that needs to import that code. But import foobar
doesn't work; I would have to rename the file to foobar.py
.
Is there some other way to import a Python module that doesn't have the .py extension?
You can use the imp.load_source
function (from the imp
module), to load a module dynamically from a given file-system path.
import imp
foobar = imp.load_source('foobar', '/path/to/foobar')
This SO discussion also shows some interesting options.