Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

I tried just converting it to a package by adding __init__.py and doing from Foo import * but it didn't work the way I had hoped.

1 Answer

0 votes
by (106k points)

To  load all modules in a folder put them as __all__ variable in __init__.py

from os.path import dirname, basename, isfile, join 

import glob 

modules = glob.glob(join(dirname(__file__), "*.py")) __all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

Related questions

0 votes
2 answers
0 votes
1 answer
asked Jan 4, 2021 in Azure by dante07 (13.1k points)
0 votes
1 answer
asked Sep 16, 2019 in Java by Anvi (10.2k points)

Browse Categories

...