How do I import other Python files?
python, python-import, python-module, python-packaging
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:
- Just `import file` without the .py extension
- A folder can be marked as a package, by adding an empty `__init__.py` file
- You can use the `__import__` function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))
Type `help(__import__)` for more details.
Problem
How do I import files in Python? I want to import: - a file (e.g. `file.py`) - a folder - a file dynamically at runtime, based on user input - one specific part of a file (e.g. a single function)
Related problems
- How to load all modules in a folder?
- Python in VSCode: Set working directory to python file's path everytime
- Alternative to execfile in Python 3?
- What's the difference between a module and package in Python?
- Python: Best way to add to sys.path relative to the current running script
- beyond top level package error in relative import