You should use the module glob for this task: https://docs.python.org/3/library/glob.html
Or just use pathlib: https://docs.python.org/3/library/pathlib.html
And for importing, importlib: https://docs.python.org/3/library/importlib.html
I guess you want to have something like a plugin directory and your script should load them dynamically.
But this is only the half work. Somewhere you've to register this loaded plugins, to announce them in your
main program.
Instead of using
Or just use pathlib: https://docs.python.org/3/library/pathlib.html
And for importing, importlib: https://docs.python.org/3/library/importlib.html
I guess you want to have something like a plugin directory and your script should load them dynamically.
But this is only the half work. Somewhere you've to register this loaded plugins, to announce them in your
main program.
import glob import importlib import pathlib # without pathlib # using module glob plugindirectory = 'plugins' loaded_plugin_modules = [] for file in glob.glob1(plugindirectory, '*.py'): stem, suffix = file.rsplit('.', 1) to_import = 'plugins.{}'.format(stem) print('Importing:', to_import) module = importlib.import_module(to_import) loaded_plugin_modules.append(module) print(loaded_plugin_modules) # with pathlib print('Using pathlib.Path') plugindirectory = pathlib.Path('plugins') loaded_plugin_modules = [] for file in plugindirectory.glob('*.py'): to_import = 'plugins.{}'.format(file.stem) print('Importing:', to_import) module = importlib.import_module(to_import) loaded_plugin_modules.append(module) print(loaded_plugin_modules)
Instead of using
stem, suffix = file.rsplit('.', 1)
, you can use also stem, suffix = os.path.splitext(file)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!