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
Finding Moving Average from Data Points in Python
How to Merge Multiple Lists into One List in Python
Python: Fastest Way to Create a List of N Lists
Double Precision Floating Values in Python
Efficient Way to Remove Keys with Empty Strings from a Dict
Multithreaded Web Server in Python
How to Use If/Else in a Dictionary Comprehension
Anaconda/Conda - Install a Specific Package Version
Call Class Method from Another Class
Is There a Difference Between Using a Dict Literal and a Dict Constructor
Too Many Values to Unpack Calling Cv2.Findcontours
How to Merge Images into a Canvas Using Pil/Pillow
Python Library 'Unittest': Generate Multiple Tests Programmatically
How to Sort a Pandas Dataframe by Index
Destroywindow Does Not Close Window on MAC Using Python and Opencv