Search code examples
python-3.xpython-importfilenamespython-importlib

How Can I Import A Python 3 Module With A Period In The Filename?


What is the proper way to import a script that contains a period, such as program_1.4.py, ideally using importlib?

(Now that the imp module is deprecated, this this answer no longer applies: How to reference python package when filename contains a period .)


Solution

  • After looking through the CPython quite a lot and coming back to some other solutions (especially Import arbitrary python source file. (Python 3.3+)), I realized that I needed to pass the full path to my module. Here is the cross-platform, call-location-independent solution:

    """

    import os, sys # For running from Notepad++ shortcut, etc
    import importlib.machinery
    
    program_1_4 = importlib.machinery.SourceFileLoader('program_1.4', os.path.join(sys.path[0], 'program_1.4.py')).load_module()
    
    print(program_1_4)
    program_1_4.main()
    

    """