擅长:python、mysql、java
<p>如果在模块中转换文件夹本身,通过使用<code>__init__.py</code>文件并使用<code>from <foldername> import *</code>适合您,则可以遍历文件夹内容
使用“os.listdir”或“glob.glob”,并使用内置函数导入以“.py”结尾的每个文件:</p>
<pre><code>import os
for name in os.listdir("plugins"):
if name.endswith(".py"):
#strip the extension
module = name[:-3]
# set the module name in the current global name space:
globals()[module] = __import__(os.path.join("plugins", name)
</code></pre>
<p>这种方法的好处是:它允许您动态地将模块名传递给<code>__import__</code>,而“import”语句需要对模块名进行硬编码,并且它允许您在导入文件之前检查有关文件的其他内容(可能是文件大小,或者如果它们导入了某些必需的模块)。</p>