'How to write a list of parameter names and their values to a text file?

I have the following issue with my python script. There are a lot of calculations, and I want to write some of the final results into a text file.

This is what I have tried so far :

a1=3
a2=5
a3=10
a4=15

setupfile = open("setupfile.txt","w")
x = [a1,a2,a4]
for name in x:
    setupfile.write("name" + "=" + repr(name) +"\n")
setupfile.close()

Current output :

name=3
name=5
name=15

Expected output :

a1=3
a2=5
a4=15


Solution 1:[1]

You can refer this answer for getting the variable name from the variable. I have modified the namestr function there to get the variable name containing the letter a. This is because the names variable inside it contains values such as ['a1', 'name', '_96', '_97', '_134']

Also it is better to use with while opening files since it gets closed after the work is done.

a1,a2,a3,a4 = 3,5,10,15

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,a4]
    for name in x:
        setupfile.write(namestr(name, globals()) + "=" + repr(name) +"\n")
    setupfile.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj