I am in a file called end.py.
In my current directory I have x number of .py files.
Each of these .py files returns a variable called total.
Is it possible, in end.py, to loop through all .py files in the current directory (apart from itself – end.py) and import each file’s total variable & ultimately store the value of each total variable in a list to be used later on in end.py?
>Solution :
You can list the Python files in the current directory:
import pathlib
source_files = pathlib.Path('.').glob('*.py')
Using importlib, you can import these in a loop:
import importlib.util
import pathlib
for source_file in pathlib.Path('.').glob('*.py'):
name = source_file.stem
spec = importlib.util.spec_from_file_location(name, source_file)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
In the for loop, you can access the total as mod.total.
To skip a single file, like end.py, you can add:
import importlib.util
import pathlib
for source_file in pathlib.Path('.').glob('*.py'):
name = source_file.stem
if name == 'end':
continue
spec = importlib.util.spec_from_file_location(name, source_file)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
Note that this will import every module in the current directory. Does that include the current module? You will probably want to skip that one too.