How to load all modules in a folder?

后端 未结 18 1995
失恋的感觉
失恋的感觉 2020-11-22 05:37

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py         


        
18条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:22

    This is the best way i've found so far:

    from os.path import dirname, join, isdir, abspath, basename
    from glob import glob
    pwd = dirname(__file__)
    for x in glob(join(pwd, '*.py')):
        if not x.startswith('__'):
            __import__(basename(x)[:-3], globals(), locals())
    

提交回复
热议问题