Python Searching for files and Importing them

141 views Asked by At

I need to write a function that walks through directories searching for files that end in _prj.py, and then extract some lists from there. The way I'm doing it right now is by using os.path.walk and then importing. My code looks like this:

for py_file in files:
    if py_file.endswith("_prj.py"):
        print py_file[:-3]
        module = py_file[:-3]
        import module

However, I get an import error:

ImportError: No module named module

I think I understand why, I'm just not sure how I would make the import statement work. Is there a way to make the module variable be read as the file name instead of "module"?

1

There are 1 answers

2
ZdaR On BEST ANSWER

The correct way of import a module by a String name is by using another module known as importlib

import importlib

math_module = importlib.import_module("math")

print math_module.sqrt(25)
>>> 5.0