-2

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?

Ros
  • 11
  • 4
  • 1
    Do the `y = __import__(...)`, then `for attr, val in vars(y).items(): ...`…? – deceze Feb 09 '21 at 14:23
  • had you added if `__name__ == "__main__":` in vars1? – I-am-developer-9 Feb 09 '21 at 14:23
  • @I-am-developer-9 nope, I haven't, how would that help? I read something about it but I don't get the usefulness in this context – Ros Feb 09 '21 at 14:38
  • @Ros actually `if __name__ == "__main__":` force the script to run only if the script is calling not in import. Can be a problem not sure – I-am-developer-9 Feb 09 '21 at 14:40
  • @deceze that is interesting but I wouldn't know what to do inside that loop then... I tried a `print(attr,val)` and it does print the variables, among other things – Ros Feb 09 '21 at 14:42
  • 2
    What *do* you want to do in the first place? Looping through a bunch of files and importing all their variables seems… suspicious…? Not as in "malicious", but as in "there's probably a better solution to whatever it is you're trying to do"… – deceze Feb 09 '21 at 14:46
  • @I-am-developer-9 I'm sorry, I can't follow you, can you write an extended example? – Ros Feb 09 '21 at 14:47
  • @Ros in your var1 script there is a chance that after import you wrote this line as every tutorial giver do `if __name__ == "__main__": #code`. If you used this the script won't execute in importing that. You can only execute the script by running var1.py – I-am-developer-9 Feb 09 '21 at 14:51
  • @deceze I'm running some simulations and every time I run the code I change the input parameters of the simulation. I have everything defined in the vars files so I don't have to change them by hand every time. – Ros Feb 09 '21 at 14:51
  • can you tell or give the code of var1 script. Couldn't know what code is of var1 or is there any or not @Ros – I-am-developer-9 Feb 09 '21 at 14:52
  • 1
    Then your simulation should be defined in a function which takes parameters, and those parameters can be defined in files, probably preferably some text format like YAML, which is pretty close to plain Python variables, and you can load those values from the file into a dict, and pass them as arguments into your function using `my_simulation(**kwargs)`…? – deceze Feb 09 '21 at 14:53
  • @I-am-developer-9 ok, now I get it. That line wasn't in my code, so that is not the problem. Thanks! – Ros Feb 09 '21 at 14:53
  • @deceze I see your point and it's probably a good idea. But it would require some rewriting of the vars files since there are ifs, parameter interpolations, and stuff for ease of reuse of the vars files text. I was hoping for some dirt quick command. I will consider rewriting everything if there is no solution of the kind I was looking for, thanks. – Ros Feb 09 '21 at 15:02
  • 1
    At the very least you can import a module as object (`y = __import(..)__`), then all variables defined in it are attributes on that object. Worst case you make a dict from that programmatically and pass them as `**kwargs` into your simulation function. There's no need to extract them as individual variables. – deceze Feb 09 '21 at 15:10
  • I would use the os module (part of the python standard lib) and read all files in a specified path – swagless_monk Feb 09 '21 at 15:21
  • Does this answer your question? [Python: import every module from a folder?](https://stackoverflow.com/questions/10043485/python-import-every-module-from-a-folder) – Tomerikoo Feb 09 '21 at 18:08
  • @Tomerikoo no, that focuses on importing all the files at once, I need them one at a time so that I can work with the variables each one contains. Thanks anyways – Ros Feb 09 '21 at 18:27

1 Answers1

1

Based on @swagless_monk's comment I started looking into python's built-in functions and found that this will do the job:

import glob
var_files = glob.glob('./vars*') 
for var_file in var_files: 
     o=open(var_file)  
     r=o.read()       
     exec(r) 
    
     # .....rest of the code working with the imported variables...

Thanks for the interest to all.

Ros
  • 11
  • 4