How can I import a dotted name file in python?
I don't mean a relative path, but a filename starting or containing a dot "."
For example: '.test.py'
is the filename.
import .test
will search for a test
package with a py
module in a parent package.
The situation is tricky, because dots mean subpackage structure to Python. Recommend to simply rename your modules instead, if that's an option!
However, importing a source file directly is still possible:
Using imp
:
import imp
my_module = imp.load_source("my_module", ".test.py")
The imp module is deprecated in favour of importlib and slated for removal in Python 3.12. Here is a Python 3 replacement:
import importlib.util
spec = importlib.util.spec_from_file_location(
name="my_module", # note that ".test" is not a valid module name
location="/path/to/.test.py",
)
my_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With