Using python, I've got the following list:
data = ['element0', 'element1', 'element2', 'element3']
for x in data:
open("myfile.txt", "w").write(x + "\n")
Just open the file object once:
with open("myfile.txt", "w") as fobj: for x in data: fobj.write(x + "\n")
I'm using the file as a context manager by passing it to the
with statement; this ensures that the file is closed again after the block of code finishes.
Each time you open the file object with the
'w' (write) mode, the file is truncated, emptied out. You'd have to use the
'a' (append) mode to prevent the file being truncated.
However, opening the file just once is much more efficient.