Import with dot name in python

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: '' 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 sub-package structure to Python. I recommend simply renaming your modules instead, if that's an option!

    However, importing a source file directly is still possible:

    Python 2

    Using imp:

    import imp
    my_module = imp.load_source("my_module", "")

    Python 3

    The imp module was deprecated in favor of importlib and has been removed 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
    my_module = importlib.util.module_from_spec(spec)