-1

I want to save all values (cases1) in a text file. But, when I execute the following code only the last value i.e 7 is saved in the variables.txt

       cases1 = [1, 2, 3, 4, 5, 6,7]
       for j in cases1:
           promfac=j
           dict = {'promfac':promfac}
           varsave=repr(dict)
           file = open("variables.txt","w")
           file.write(varsave + '\n')
           file.close()

Following is the output:

{'promfac': 7}

I want my output to be like this:

{'promfac': 1}
{'promfac': 2}
{'promfac': 3}
{'promfac': 4}
{'promfac': 5}
{'promfac': 6}
{'promfac': 7}
ywbaek
  • 2,971
  • 3
  • 9
  • 28

2 Answers2

1

U should open you file outside the for loop if u are using ‘w’ or w+. Else use ‘a’. It looks like you are overwriting your file all the time instead of appending the file

Emerson
  • 1,136
  • 1
  • 6
  • 9
0

You should use a instead of w in your code.

Or you can open it with w and loop over your list and store it line by line like this:

cases1 = [1, 2, 3, 4, 5, 6, 7]
with open("variables.txt", "w") as file:
    for i in case1:
        varsave = repr({'promfac': i})
        file.write(varsave + '\n')
Binh
  • 1,143
  • 6
  • 8