<p>The <code>csv.writer</code> module directly controls line endings and writes <code>\r\n</code> into the file directly. In <strong>Python 3</strong> the file must be opened in untranslated text mode with the parameters <code>'w', newline=''</code> (empty string) or it will write <code>\r\r\n</code> on Windows, where the default text mode will translate each <code>\n</code> into <code>\r\n</code>.</p>
<pre><code class="lang-auto">#!python3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
</code></pre>
<p>If using the <code>Path</code> module:</p>
<p>from pathlib import Path<br>
import csv</p>
<p>with Path(‘/pythonwork/thefile_subset11.csv’).open(‘w’, newline=‘’) as outfile:<br>
writer = csv.writer(outfile)</p>
<pre><code class="lang-auto">
If using theStringIO` module to build an in-memory result, the result string will contain the translated line terminator:
</code></pre>
<p>from io import StringIO<br>
import csv</p>
<p>s = StringIO()<br>
writer = csv.writer(s)<br>
writer.writerow([1,2,3])<br>
print(repr(s.getvalue())) # ‘1,2,3\r\n’ (Windows result)</p>
<pre><code class="lang-auto">
If writing that string to a file later, remember to use newline='':
</code></pre>
<h1><a name="p-16770-built-in-open-1" class="anchor" href="#p-16770-built-in-open-1" aria-label="Heading link"></a>built-in open()</h1>
<p>with open(‘/pythonwork/thefile_subset11.csv’, ‘w’, newline=‘’) as f:<br>
f.write(s.getvalue())</p>
<h1><a name="p-16770-paths-open-2" class="anchor" href="#p-16770-paths-open-2" aria-label="Heading link"></a>Path’s open()</h1>
<p>with Path(‘/pythonwork/thefile_subset11.csv’).open(‘w’, newline=‘’) as f:<br>
f.write(s.getvalue())</p>
<h1><a name="p-16770-paths-write_text-added-the-newline-parameter-to-python-310-3" class="anchor" href="#p-16770-paths-write_text-added-the-newline-parameter-to-python-310-3" aria-label="Heading link"></a>Path’s write_text() added the newline parameter to Python 3.10.</h1>
<p>Path(‘/pythonwork/thefile_subset11.csv’).write_text(s.getvalue(), newline=‘’)</p>
<pre><code class="lang-auto">
In Python 2, use binary mode to open outfile with mode 'wb' instead of 'w' to prevent Windows newline translation. Python 2 also has problems with Unicode and requires other workarounds to write non-ASCII text. See the Python 2 link below and the UnicodeReader and UnicodeWriter examples at the end of the page if you have to deal with writing Unicode strings to CSVs on Python 2, or look into the 3rd party unicodecsv module:
</code></pre>
<p>#!python2<br>
with open(‘/pythonwork/thefile_subset11.csv’, ‘wb’) as outfile:<br>
writer = csv.writer(outfile)</p>
<pre><code class="lang-auto">
Documentation
(Réponse tronquée)</code></pre>