擅长:python、mysql、java
<p>在Python 2中,使用模式<code>'wb'</code>而不是<code>'w'</code>打开<code>outfile</code>。<code>csv.writer</code>直接将<code>\r\n</code>写入文件。如果您不在<em>二进制</em>模式下打开文件,它将写入<code>\r\r\n</code>,因为在Windows<em>上,text</em>模式将把每个<code>\n</code>转换为<code>\r\n</code>。</p>
<p>在Python 3中,所需的语法已更改,因此使用附加参数<code>newline=''</code>打开<code>outfile</code>。</p>
<h3>示例:</h3>
<pre><code># Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
writer = csv.writer(outfile)
# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
</code></pre>
<h3>文档链接</h3>
<ul>
<li><a href="https://docs.python.org/2/library/csv.html#csv.writer" rel="noreferrer">https://docs.python.org/2/library/csv.html#csv.writer</a></li>
<li><a href="https://docs.python.org/3/library/csv.html#csv.writer" rel="noreferrer">https://docs.python.org/3/library/csv.html#csv.writer</a></li>
</ul>