6

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

malekcellier
  • 177
  • 3
  • 10

7 Answers7

2

It is possible to find the name of a variable, a called function can get its caller's variables using:

import sys

def save_variable_to_file(var):

     names = sys._getframe(1).f_globals
     names.update(sys._getframe(1).f_locals)
     for key in names.keys():
         if names[key] == var: 
             break

     if 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 glob

for 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.

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

No, this won't work. When you write the variable name there, it gives the value of the variable, 3.14 and so on, to save_variable_to_file(). Try one of these variants:

d = dict(my_variable_name=3.14)
save_variable_to_file('my_variable_name', d['my_variable_name'])

or:

var_name = 'my_variable_name'
d = {var_name: 3.14}
save_variable_to_file(var_name, d[var_name])

Here is a good tutorial, that you should definitely go through, if you're serious about learning Python.

Michael
  • 7,316
  • 1
  • 37
  • 63
  • And how should `save_variable_to_file()` know the file name if only the content is given to it? – glglgl Oct 02 '12 at 09:55
  • 2
    These do exactly the same thing; they pass the value, not the name. `save_variable_to_file` needs 2 pieces of information; a name and a value (or a place to look up the name to get the value). – Ben Oct 02 '12 at 09:56
0

Unfortunately it is not possible to find out the name of a variable. Either you extend your function to also allow a string as a parameter, or you have to use another solution:

save_variable_to_file("variableName1", variableName1)

Another solution would be to store your variables within a dict which allows the retrieval of the keys as well:

myVariables = {}
myVariables["variableName1"] = 3.14


for key, value in myVariables.items():
    save_variable_to_file(key, value)
Constantinius
  • 34,183
  • 8
  • 77
  • 85
0

How about using a dict:

var_dict = {'variable1': 3.14, 'variable2':1.09}
for key, value in var_dict.items():
    with open('path\%s'%key, "w") as file:
        file.write(value)
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 1
    Thanks for the 2 solutions: either passing both the name as a string and the variable, or creating a dictionary and then read the name from there. I think it should work fine either way. Thanks again. – malekcellier Oct 02 '12 at 09:55
0
for key, value in locals().items():
    with open(key + '.txt', 'w') as f:
        f.write(value)

should do your trick - as long as all locally defined variables are to be considered.

A far better solution, however, would be to put all you need into a dict and act as the others already proposed.

You could even do this:

def save_files(**files):
    for key, value in files.items():
        with open(key + '.txt', 'w') as f:
            f.write(value)

and then

save_files(**my_previously_defined_dict)
save_files(**locals()) # as example above
save_files(filename='content')
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Itering over all locals() will be a huge mess, you should at least make sure, that only keys not starting with `_` are taken into account. – Michael Oct 02 '12 at 10:13
  • I have hundreds of variables and this operation is meant to be done 500times per second for several minutes. Won't this way result in a lot of for-loop overhead, and hence slow down the program? – malekcellier Oct 02 '12 at 10:16
  • @Michael It was intended as a first approach, in this case needing a bit of optimization - as I wrote, "as long as /all/ locally defined variables are to be considered". If this is not the case, th code must be modified, e.g. in the way you suggest. – glglgl Oct 02 '12 at 10:22
  • @user1713952 It sounds like quite a lot of work - what alternatives do you think you have? – glglgl Oct 02 '12 at 10:23
  • 1
    @user1713952: If you have hundreds of variables, and you don't have them in their own namespace to simply iterate over them as key-value-pairs, you definitely have done something wrong in your program. Anyways, more details about the problem, and you'll get better answers. – Michael Oct 02 '12 at 10:30
  • I suggested this line as edit in your post. If it is as he says, it could actually be a valid solution. – Michael Oct 02 '12 at 10:33
0

Variables don't have names. When your script runs it creates one or more identifiers for some of the objects it interacts with commonly called variables, but these are temporary and cease to exist when the program ends. Even if you save them, you will then be faced with the reverse problem of how to turn them back into an identifier with saved name associated with the saved value.

martineau
  • 119,623
  • 25
  • 170
  • 301
0

If you want to get the name of your variable as string, use python-varname package (python3):

from varname import nameof

s = 'Hey!'

print (nameof(s))

Output:

s

Get the package here:

https://github.com/pwwang/python-varname

Synthase
  • 5,849
  • 2
  • 12
  • 34