tags:

views:

182

answers:

3

I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it:

import foobar

But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension?

Update: the file has no extension because I also use it as a standalone script, and I don't want to type the .py extension to run it.

Update2: I will go for the symlink solution mentioned below.

+3  A: 

You can use the imp.load_source(path) function (from the imp module), to load a module dynamically from a given file-system path.

This SO discussion also shows some interesting options.

Eli Bendersky
+3  A: 

imp.load_source(module_name, path) should do or you can do the more verbose imp.load_module(module_name, file_handle, ...) route if you have a file handle instead

Daniel DiPaolo
+3  A: 

Like others have mentioned, you could use imp.load_source, but it will make your code more difficult to read. I would really only recommend it if you need to import modules whose names or paths aren't known until run-time.

What is your reason for not wanting to use the .py extension? The most common case for not wanting to use the .py extension, is because the python script is also run as an executable, but you still want other modules to be able to import it. If this is the case, it might be beneficial to move functionality into a .py file with a similar name, and then use foobar as a wrapper.

Brendan Abel
Or instead of wrapping, just symlink foobar.py to foobar (assuming you aren't on Windows)
whaley
@whaley, yeah, that would be much cleaner. You could use a .bat for windows to accomplish the same thing.
Brendan Abel