I have written some code in Python and I would like to save some of the variables into files having the name of the variable.
The following code:
variableName1 = 3.14
variableName2 = 1.09
save_variable_to_file(variableName1) # function to be defined
save_variable_to_file(variableName1)
should create 2 files, one named variableName1.txt and the other one variableName2.txt and each should contain the value of the corresponding variable at the time the function was called.
This variable name is supposed to be unique in the code.
Thanks!
HM
It is possible to find the name of a variable, a called function can get its caller's variables using:
import sysdef save_variable_to_file(var):names = sys._getframe(1).f_globalsnames.update(sys._getframe(1).f_locals)for key in names.keys():if names[key] == var: breakif key:open(key+".txt","w").write(str(var))else:print(key,"not found")thing = 42
save_variable_to_file(thing)
But it is probably a really bad idea. Note that I have converted the value to a string, how would you want dictionaries and lists to be saved? How are you going to reconstruct the variable later?
import globfor fname in glob.iglob("*.txt"):vname = fname.rstrip(".txt")value = open(fname).read()exec(vname + "=" + value)print(locals())
Using something like exec
can be a security risk, it is probably better to use something like a pickle, JSON, or YAML.