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.

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x