创建包含变量名作为字符串加值的txt文件 [英] creating txt file containing variablenames as string plus value
本文介绍了创建包含变量名作为字符串加值的txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个包含给定变量列表的文件,例如:
I want to create a file with takes a given list of variables for example:
a1 = 3
a2 = 3
a3 = 4
a4 = 6
a5 = 'test'
a6 = 19
a7 = 19
输出应如下所示:
test.txt
a1 = 3
a2 = 3
a3 = 4
a4 = 6
a5 = 'test'
a6 = 19
a7 = 19
txt文件的内容.
建立模型是必需的.
我尝试过这种方式:
def namestr(obj, namespace):
names = [name for name in namespace if namespace[name] is obj]
name = [n for n in names if 'a' in n]
return name[0]
with open("setupfile.txt", "w") as setupfile:
x = [a1, a2, a3, a4, a5, a6, a7]
for name in x:
print(name)
setupfile.write(namestr(name, globals()) + "=" + repr(name) +"\n")
print(repr(name))
setupfile.close()
但这不是一个足够的解决方案.具有相同值的变量在文本文件中具有相同的名称.
But this is not a sufficient solution. The variables with same values are having the same name in the textfile.
是否有更好的解决方案来创建如上所述的文本文件?也许是获取变量名称的更好方法.
Is there a better solution to create a textfile as described? Maybe a better way to get the name of the variables.
推荐答案
我遇到了同样的问题.如果可能的话,您应该尝试这种方式.
I've had the same issue. You should probably try it this way, if it works for you.
class NewClass(object): pass
names = NewClass()
vars = ['a1', 'a2', 'a3','a4','a5','a6','a7']
for v in vars:
setattr(names, v, eval(v))
with open("setupfile.txt","w") as setupfile:
members = [attr for attr in dir(names) if not callable(getattr(names, attr)) and not attr.startswith("__")]
for i in range(0,len(members)):
#print(name)
setupfile.write(members[i] + '=' + str(getattr(names, members[i])) + "\n")
#print(repr(name))
setupfile.close()`
这篇关于创建包含变量名作为字符串加值的txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文