Bruno F. Bruno F. - 1 year ago 93
Python Question

How can I write each element of a list to each line of a text file?

Using python, I've got the following list:

data = ['element0', 'element1', 'element2', 'element3']

And I want to write each element, into a new line of "myfile.txt", so I've been trying this:

for x in data:
open("myfile.txt", "w").write(x + "\n")

Which gives me this (inside "myfile.txt"):


I looks like each time it goes through the loop, it writes the element on top of the last.

Desired result (inside "myfile.txt"):


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download