Posted By: Anonymous
How do I import other files in Python?
- How exactly can I import a specific python file like
- How can I import a folder instead of a specific file?
- I want to load a Python file dynamically at runtime, based on user
- I want to know how to load just one specific part from the file.
For example, in
main.py I have:
from extra import *
Although this gives me all the definitions in
extra.py, when maybe all I want is a single definition:
def gap(): print print
What do I add to the
import statement to just get
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:
import filewithout the .py extension
- A folder can be marked as a package, by adding an empty
- 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))
help(__import__) for more details.