我想用importlib将文件导入为python模块。此文件没有.py
但.cfg
扩展名。它包含python代码。
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.load_source('myconfig', 'conf.cfg').foo
'bar'
>>> import importlib
>>> importlib.import_module('conf.cfg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2212, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked
ImportError: No module named 'conf'
我可以使用imp.load_source
执行此操作,但已弃用。使用importlib.import_module
转换.
作为模块探索。
如何使用importlib导入conf.cfg
文件?