snippetpythonCriticalCanonical
How do I import other Python files?
Viewed 0 times
howotherfilespythonimport
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)
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 filewithout the .py extension
- A folder can be marked as a package, by adding an empty
__init__.pyfile
- 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.Context
Stack Overflow Q#2349991, score: 561
Revisions (0)
No revisions yet.