In my code, I want to execute import filename for all the files that are present in a directory. I have a file abc.py under workspace. I am currently doing the following :
for filename in os.listdir(homedir/workspace) exec "import " + filename filename = eval(filename + '.function(variable)') The problem is that instead of doing import abc, it is doing import abc.py, and then showing the error no module named py
How can I resolve this?
Thanks in advance!
exec. You can achieve exactly the same effect with:module = __import__(filename). Usingexecyou are opening a security issue (e.g. someone can name a fileos;os.sytem("killall cats")and when the code in your question executes all the cats will die! Using__import__you would only receive anImportError. Even better than__import__isimportlib.import_module, although it works in python2.7 and 3.1+ only.