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.
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.
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.
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.
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.
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')]
Add the __all__
Variable to __init__.py
containing:
__all__ = ["bar", "spam", "eggs"]
See also http://docs.python.org/tutorial/modules.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With