Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I import from a file if I don't know the file name until run time?

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.

like image 250
RobertL Avatar asked Oct 21 '22 21:10

RobertL


1 Answers

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!

like image 53
aIKid Avatar answered Jan 02 '23 19:01

aIKid