How to reference python package when filename contains a period
Actually, you can import a module with an invalid name. But you'll need to use imp
for that, e.g. assuming file is named models.admin.py
, you could do
import imp
with open('models.admin.py', 'rb') as fp:
models_admin = imp.load_module(
'models_admin', fp, 'models.admin.py',
('.py', 'rb', imp.PY_SOURCE)
)
But read the docs on imp.find_module
and imp.load_module
before you start using it.
If you really want to, you can import a module with an unusual filename (e.g., a filename containing a '.' before the '.py') using the imp module:
>>> import imp
>>> a_b = imp.load_source('a.b', 'a.b.py')
>>> a_b.x
"I was defined in a.b.py!"
However, that's generally a bad idea. It's more likely that you're trying to use packages, in which case you should create a directory named "a", containing a file named "b.py"; and then "import a.b" will load a/b.py.
The file is called models/admin.py
. (Source)
That is, it should be called admin.py
in a directory called models
.
Then you can import using from models.admin import *
, assuming that it is in your Python path.
No, you can't import a python file as a module if its name contains a period (or a question mark, or exclamation mark, etc). A python module's name (not including the .py) must be a valid python name (ie can be used as a variable name).