Skip to content Skip to sidebar Skip to footer

How To Call A Function From Every Module In A Directory In Python?

What I want to do is import every module in a directory/package and then call the same function on each submodule, without knowing their names or how many there are. If you're fami

Solution 1:

Find every module in that directory, use __import__ to import it, then call the function. For example:

for file_name in os.listdir('path/to/modules'):
    if file_name.startswith('.') or not file_name.ends_with('.py'):
        continuemodule_name= file_name[:-3]
    module = __import__(module_name)
    module.some_function()

However, this does not account for all cases—in particular, some modules might be written in C and have the .pyd extension rather than .py. Do you want to account for that? There are probably several entries in sys.path. Do you want to support all of them, or only search one directory? Modules can reside inside of a ZIP file. You would have to support that. And with import hooks, modules could probably be generated on the fly, and there might be no way to enumerate them. You have to decide how far you want to go when searching for modules. But after you’ve found them, it’s easy to import and use them.

Post a Comment for "How To Call A Function From Every Module In A Directory In Python?"