简体   繁体   中英

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM