0

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
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Lorschi
  • 36
  • 5
  • Do you want the text file to contain `a1=3, a2=5, a4=15` in separate lines ? – Suraj Jul 10 '20 at 09:23
  • Yes, this is exactly what i want – Lorschi Jul 10 '20 at 09:27
  • 1
    @Vallepu Put all the relevant variables in a `dict`. Then you can simply do `for item in mydict.items(): setupfile.write('%s = %s\n' % item)`. Or even better, you could just read and write the whole `dict` using the [json module](https://docs.python.org/3/library/json.html#module-json). – ekhumoro Jul 10 '20 at 09:55
  • Does this answer your question? [How to create a text file containing variable names as string plus their values?](https://stackoverflow.com/questions/62943768/how-to-create-a-text-file-containing-variable-names-as-string-plus-their-values) – Gino Mempin May 23 '22 at 11:39
  • I've figured out a different solution, that allows me to have different variables with the same value. In case anyone is looking for the same answer, you'll find it right here: https://stackoverflow.com/questions/62943768/creating-txt-file-containing-variablenames-as-string-plus-value/62944437#62944437 – Lorschi Jul 23 '20 at 18:36

1 Answers1

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()
Suraj
  • 2,253
  • 3
  • 17
  • 48
  • Tank you very much! I've seen the other answer before, but didn't realize that it fits to my problem – Lorschi Jul 13 '20 at 06:37