'Import python file of parameter values and options within a for loop
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.
Solution 1:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anshumaan Mishra |
