Python 正在搜索文件并导入它们

Python Searching for files and Importing them

我需要编写一个函数来遍历目录搜索以 _prj.py 结尾的文件,然后从那里提取一些列表。我现在的做法是使用 os.path.walk 然后导入。我的代码如下所示:

for py_file in files:
    if py_file.endswith("_prj.py"):
        print py_file[:-3]
        module = py_file[:-3]
        import module

但是,我收到一个导入错误:

ImportError: No module named module

我想我明白为什么,我只是不确定如何使 import 语句起作用。有没有办法让模块变量被读取为文件名而不是 "module"?

通过字符串名称导入模块的正确方法是使用另一个名为 importlib

的模块
import importlib

math_module = importlib.import_module("math")

print math_module.sqrt(25)
>>> 5.0