tags:

views:

69

answers:

3

Is there any way to import all modules in the current directory, and return a list of them?

For example, for the directory with:

  • mod.py
  • mod2.py
  • mod3.py

It will give you [<module 'mod'>, <module 'mod2'>, <module 'mod3'>]

+1  A: 

See this SO thread for a few different ways to do it.

Kaleb Brasee
Thanks. I found this, and it was helpful too: http://stackoverflow.com/questions/67631/how-to-import-module-from-file-name
Jeffrey Aylesworth
A: 

I hope this is what you mean

import os

listOfMods = []
for i in os.listdir(pathToDirWithModules):
    if i[-3:] == '.py':
        modname = i[i.rfind('/'):-3]  # '/' for windows '\\' for linux
        eval("import " +modname)
        listOfMods.append(modname)

return listOfMods
inspectorG4dget
A: 

this should work

 import glob
    foo=glob.glob("*.py")

    print foo #prints the list of py files

    # to import the modules,this should work

    for i foo:
          eval("import " + i)
appusajeev
That doesn't give me all imported modules as a list
Jeffrey Aylesworth