Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load all modules in a folder?

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.

like image 733
Evan Fosmark Avatar asked Jun 29 '09 09:06

Evan Fosmark


People also ask

How do I load all files in a directory in Python?

Open All the Files in a Directory With the os. listdir() Function in Python. The listdir() function inside the os module is used to list all the files inside a specified directory. This function takes the specified directory path as an input parameter and returns the names of all the files inside that directory.

How do I import a whole module?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

What is __ all __?

Python __all__ is a variable that can be set in the __init__.py file of a package. The __all__ variable is a list of strings that defines those symbols that are imported when a program does.

Can you import multiple modules in Python?

You can import multiple functions, variables, etc. from the same module at once by writing them separated by commas. If a line is too long, you can use parentheses () to break the line.


2 Answers

List all python (.py) files in the current folder and 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')] 
like image 174
Anurag Uniyal Avatar answered Oct 25 '22 06:10

Anurag Uniyal


Add the __all__ Variable to __init__.py containing:

__all__ = ["bar", "spam", "eggs"] 

See also http://docs.python.org/tutorial/modules.html

like image 23
stefanw Avatar answered Oct 25 '22 06:10

stefanw