There's a highly upvoted StackOverflow thread which says that the best way to run Python files within another Python file is to import
them as a module.
That works well for me, except that I'm having trouble doing it programmatically in a case where there are at least hundreds (if not thousands) of files to be run.
All of the files are in the same directory and share a common naming convention. I tried to run them like this:
import glob, os
for filename in glob.glob("*_decomp*"):
import filename
but that throws an error:
Traceback (most recent call last): File "C:\Python35\lib\site-packages\IPython\core\interactiveshell.py", line
3066, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 4, in import filename File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.3\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ImportError: No module named 'filename'
The variable filename
is also underlined in red in the IDE, which negates my original hypothesis that it was simply a matter of needing to remove the .py file extension.
This works fine for printing:
import glob, os
for filename in glob.glob("*_decomp*"):
# import filename
print(filename)
So I'm not really sure what the problem with the earlier statement is or how to work around it. I can also do the import
manually and that works fine, but again I'd like to do it programmatically so that I don't have to type all of the file names and because the file names will change over time.
Finally, I also tried it with [:-3]
(i.e. filename[:-3]
) to remove the file extension, but again that only works for print()
and not import
.