擅长:python、mysql、java
<p>我更喜欢使用标准库中的<a href="https://docs.python.org/2/library/csv.html?highlight=csv#module-csv" rel="noreferrer">^{<cd1>}</a>模块和<a href="https://docs.python.org/2/reference/compound_stmts.html#the-with-statement" rel="noreferrer">^{<cd2>}</a>语句来避免文件处于打开状态。</p>
<p>关键是在打开文件时使用<code>'a'</code>进行追加。</p>
<pre><code>import csv
fields=['first','second','third']
with open(r'name', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
</code></pre>
<p>如果您使用的是Python2.7,那么在Windows中可能会遇到多余的新行。您可以尝试使用<code>'ab'</code>而不是<code>'a'</code>来避免它们,但是,这将导致您在Python 3.6中使用<a href="https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv">TypeError: a bytes-like object is required, not 'str' in python and CSV</a>。正如Natacha建议的那样,添加<code>newline=''</code>将导致您<a href="https://stackoverflow.com/questions/56206233/python-2-and-3-csv-module-text-binary-mode-backwards-compatibility">a backward incompatibility between Python 2 and 3</a>。</p>