Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I loop through all the .py files in my current directory & import a variable from each one?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Documentation

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading