pythonimportpython-importpython-modulepython-packaging

How do I import other Python files?


How do I import files in Python? I want to import:

  1. a file (e.g. file.py)
  2. a folder
  3. a file dynamically at runtime, based on user input
  4. one specific part of a file (e.g. a single function)

Solution

  • importlib was added to Python 3 to programmatically import a module.

    import importlib
    
    moduleName = input('Enter module name:')
    importlib.import_module(moduleName)
    

    The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

    In python 2.x:

    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))
    

    Type help(__import__) for more details.