Python中字符串的变量名 [英] Variable name to string in Python
问题描述
我已经用Python编写了一些代码,我想将一些变量保存到具有该变量名称的文件中.
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.
以下代码:
variableName1 = 3.14
variableName2 = 1.09
save_variable_to_file(variableName1) # function to be defined
save_variable_to_file(variableName1)
应创建2个文件,一个文件名为variableName1.txt,另一个文件名为variableName2.txt,每个文件都应包含调用函数时相应变量的值.
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.
谢谢!
HM
推荐答案
可以找到变量的名称,被调用的函数可以使用以下方法获取其调用者的变量:
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())
使用类似exec
的方法可能会带来安全风险,最好使用pickle,JSON或YAML之类的方法.
Using something like exec
can be a security risk, it is probably better to use something like a pickle, JSON, or YAML.
这篇关于Python中字符串的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!