擅长:python、mysql、java
<p>正如Lennart所描述的,在遍历CSV文件时,不能就地修改它。</p>
<p>如果您真的反对创建第三个文件,那么您可能需要研究使用带<a href="http://docs.python.org/2/library/stringio.html" rel="nofollow">StringIO</a>的字符串缓冲区,其思想是在内存中构建文件a的新的所需内容。在脚本结束时,可以在文件A上写入缓冲区的内容</p>
<pre><code>from cStringIO import StringIO
with open('fileB', 'rb') as file_b:
new_a_buf = StringIO()
writer = csv.writer(new_a_buf)
reader2 = csv.reader(file_b)
next(reader2)
for row in reader2:
if (row[0], row[2]) not in removal_list:
writer.writerow(row)
# At this point, the contents (new_a_buf) exist in memory
with open('fileA', 'wb') as file_a:
file_a.write(new_a_buf.getvalue())
</code></pre>