简体   繁体   English

如何创建一个包含变量名称作为字符串加上它们的值的文本文件?

[英]How to create a text file containing variable names as string plus their values?

I want to create a file that takes a given list of variables and the output should look as follows:我想创建一个包含给定变量列表的文件,output 应如下所示:

test.txt

a1 = 3
a2 = 3
a3 = 4
a4 = 6
a5 = 'test'
a6 = 19
a7 = 19

I tried this way:我试过这样:

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 the same values are having the same name in the text file.具有相同值的变量在文本文件中具有相同的名称。

Is there a better solution to create a text file 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()`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM