How can I write each element of a list to each line of a text file?
<p>Using python, I've got the following list:</p>

<pre><code>data = ['element0', 'element1', 'element2', 'element3']
</code></pre>

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

<pre><code>for x in data:
    open("myfile.txt", "w").write(x + "\n")
</code></pre>

<p>Which gives me this (inside "myfile.txt"):</p>

<pre><code>element3
</code></pre>

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

<p>Desired result (inside "myfile.txt"):</p>

<pre><code>element0
element1
element2
element3
</code></pre>

<p>Just open the file object <strong>once</strong>:</p>

<pre><code>with open("myfile.txt", "w") as fobj:
    for x in data:
        fobj.write(x + "\n")
</code></pre>

<p>I'm using the file as a <em>context manager</em> by passing it to the <code>with</code> statement; this ensures that the file is closed again after the block of code finishes.</p>

<p>Each time you open the file object with the <code>'w'</code> (write) mode, the file is <em>truncated</em>, emptied out. You'd have to use the <code>'a'</code> (append) mode to prevent the file being truncated.</p>

<p>However, opening the file just once is much more efficient.</p>

python list file