HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I import other Python files?

Submitted by: @import:stackoverflow-api··
0
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 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.

Context

Stack Overflow Q#2349991, score: 561

Revisions (0)

No revisions yet.