0

I have code that reads in parameter values and options from an external python file using import optionsFile as my, I then use these values in the rest of the code to calculate a result.

I now want to set up a series of these files and then loop through all of them in the main code. I have placed the multiple files in a folder and am using os.listdir(folderName) to get a list of the file names. However, I cannot figure out how to pull this into a for loop. The MWE below shows the gist of what I want to achieve

MWE

list_of_files = ["temp1", "temp2"]
score = 0


import temp1 as my

myans = my.cat + my.dog
score = score + myans
print(score)

score = 0
for filename in list_of_files:
    import filename as my

    myans = my.cat + my.dog

    score = score + myans
    print(score)

I tried my = importlib.import_module('temp1.py') based on some suggestions that appeared relevant, but that gives ModuleNotFound as an error.

Esme_
  • 1,360
  • 3
  • 18
  • 30
  • Does this answer your question? [How to import a module in Python with importlib.import\_module](https://stackoverflow.com/questions/10675054/how-to-import-a-module-in-python-with-importlib-import-module) – Anshumaan Mishra Apr 22 '22 at 07:15
  • 1
    Can you read the temp1.py file and extract the values instead of importing it as a module? – ytung-dev Apr 22 '22 at 07:23
  • 3
    Try removing the .py: `my = importlib.import_module('temp1')`, then you can use it with the `filename` variable – Anshumaan Mishra Apr 22 '22 at 07:24

1 Answers1

1

The importlib function takes arguments just like imports so the module name should not be followed by .py
Use it like:

my = importlib.import_module('temp1')

Then you can use it with the loop:

for filename in list_of_files:
    my = importlib.import_module(filename)
    myans = my.cat + my.dog

    score = score + myans
    print(score)
Anshumaan Mishra
  • 1,349
  • 1
  • 4
  • 19