开发者

Import all the modules in a directory

开发者 https://www.devze.com 2022-12-17 10:27 出处:网络
开发者_如何学编程Is there any way to import all modules in the current directory, and return a list of them?

开发者_如何学编程Is there any way to import all modules in the current directory, and return a list of them?

For example, for the directory with:

  • mod.py
  • mod2.py
  • mod3.py

It will give you [<module 'mod'>, <module 'mod2'>, <module 'mod3'>]


I think I've got your idea.

Try the following:

import glob
modules = []
for module_name in glob.glob("*.py"):
    modules.append(__import__(module_name[:-3]))

This way you get a list of module objects and don't pollute the global namespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消