I want to do this:
from fileName import variableName
There's no problem if I hard code fileName. But I need to it with fileName as a string variable and that doesn't seem to work.
The context of the question is that I'm trying to make a function that has the file name as an argument. The function imports variableName from whichever file is given in the argument, then returns variableName's value, which will be a list. Each of the various files that might be given in the argument contains just one python statement such as:
data = [xxxxx]
except that the content (the xxxx) is several thousand lines long. Just putting a string or a variable that evaluates to a string into the second word of the "from..." statement doesn't compile. I also tried building a string containing the whole statement then doing eval(string) but that also gives 'invalid syntax". How else can I do this? The documentation says that the 'from...' statement is not a compiler directive but is evaluated at run time, so I thought this should work.
Use the importlib.import_module
function:
import importlib
fileName = ['a','b','c']
for file in fileName:
module = importlib.import_module(file)
data.append(module.variableName)
Which is equal to:
from a import variableName
from b import variableName
from c import variableName
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With