从所有文件夹递归导入所有.py文件 [英] Recursively import all .py files from all folders

查看:110
本文介绍了从所有文件夹递归导入所有.py文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于一个根目录,我需要从该根目录下的所有文件夹(以及其他文件夹内的文件夹)中导入所有文件.

Given one root directory, I need to import all files from all folders (and folders inside other folders) under the root directory.

我认为可以在os.walk()的帮助下完成此操作,但是不知道在遍历"文件后如何导入文件.

I figured this could maybe be done with the help of os.walk(), but no idea how to import the files after "walking" through them.

有一种简单的方法吗?

推荐答案

要按名称导入模块(在3.4中),请使用importlib.load_module,这是围绕importlib.__import__的简化包装".您将在其他答案中看到提到的后者(作为内置的).为了有用,您当然必须将返回的每个模块分配给 something ,除非您只是为了检查语法或生成.pyc文件而导入,就像在compile_all模块中一样.

To import a module by name (in 3.4), use importlib.load_module, which is a "simplifying wrapper around importlib.__import__". You will see the latter mentioned (as a builtin) in other answers. To be useful, you must, of course, assign each module returned to something -- unless you are importing merely to check syntax or generate .pyc files, as in the compile_all module.

这篇关于从所有文件夹递归导入所有.py文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆