Writing a list into the file by using Python
<p>I am trying to write a list into the file. I used:</p>

<pre><code>studentFile = open("students1.txt", "w")
for ele in studentList:
    studentFile.write(str(ele) + "\n")
studentFile.close()
</code></pre>

<p>As a result, the output was:</p>

<pre><code>['11609036', 'MIT', 'NE']

['11611262', 'MIT', 'MD']

['11613498', 'BIS', 'SA']
</code></pre>

<p>instead of:</p>

<pre><code>11609036    MIT    NE

11611262    MIT    MD

11613498    BIS    SA
</code></pre>

<p>How can I fix it?</p>

<p>Use <code>.join</code> to convert each <em>sublist</em> into a string:   </p>

<pre><code>studentFile.write(' '.join(ele) + "\n")
</code></pre>

<p>You may find the <a href="https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement" rel="nofollow"><code>with</code></a> statement which creates a <em>context manager</em> a more cleaner alternative for opening, writing to, and closing files:</p>

<pre><code>with open("students1.txt", "w") as student_file:
   for ele in studentList:
       student_file.write(' '.join(ele) + "\n")
</code></pre>

<p>The space in between the items can be increased by modifying <code>' '</code> or using tab spacing as in <code>'\t'.join</code>.</p>

python