问题
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
The output should be look as follows:
test.txt
a1 = 3
a2 = 3
a3 = 4
a4 = 6
a5 = 'test'
a6 = 19
a7 = 19
Content of txt file.
It is needed for setting up a model.
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 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.
回答1:
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()`
来源:https://stackoverflow.com/questions/62943768/creating-txt-file-containing-variablenames-as-string-plus-value