Writing to a File in a for Loop Only Writes the Last Value

Writing to a file in a for loop only writes the last value

That is because you are opening , writing and closing the file 10 times inside your for loop. Opening a file in w mode erases whatever was in the file previously, so every time you open the file, the contents written to it in previous iterations get erased.

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

Writing to a file in a loop only writes once

You only execute from test.values import a once, when the script first starts. That executes values.py, which assigns the a variable.

Rewriting the file doesn't cause the import to be executed again, so you never reassign a with the new value from the file. And even if you re-executed the import statement, it wouldn't be updated, as Python remembers which modules have been imported and doesn't re-import them (see python import multiple times).

To keep adding to the value in the file, you'll need to run your whole script repeatedly, not just call changedata() in a loop. Or you could have changedata() update the a variable instead of using new.

Python for loop storing only the last value

You are overwriting the existing csv on each iteration.

To fix it, simply indicate that you want to append instead of write by

all_dfs.to_csv('final_data.csv', encoding='utf-8', mode='a')

How do I write to txt file in for loop (Python)?

Writting to file out of loop, you need move it to loop body:

with open("prime.txt", "a") as file_prime:
for num in range(2,500):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print(num)
file_prime.write(str(num)+ '\n')


Related Topics



Leave a reply



Submit