I am importing variables from some files. So far I've used the command:
from vars1 import *
Where vars1.py is the file name. Then for every vars.py
file, I would have to manually change the name of the file and rerun the code.
I'd like to be able to loop onto all the files inside the folder so that I can import them one by one and work with the variables of each file at a time, by doing something like:
import glob
var_files = glob.glob('./vars*')
for var_file in var_files:
from var_file import *
# .....rest of the code working with the imported variables....
But if I try to use a variable in the import statement it returns ModuleNotFoundError: No module named 'var_file'
. (I suspect that the glob like that doesn't work and I'd have to use some regular expression to get it to work, but you get the idea)
I haven't found an equivalent to import *
in the methods I've seen so far. In the cases I've seen I would have to use a prefix every time I need to use one of the imported variables, leading to a heavier notation and to lots of changes in the code. So far I tried:
import importlib
variable='vars1'
__import__(variable)
# or alternatively
importlib.import_module(variable)
Either of these will not keep the imported variables in memory unless I assign the import to some other variable (e.g. y=__import__(variable)
) and then use it as a prefix to access variables (e.g. y.volume
), which I'd like to avoid.
Is there a way to do this?