<p>此解决方案将<a href="http://docs.python.org/2/library/fileinput.html">^{<cd1>}</a>与<code>inplace=True</code>一起使用,后者将写入临时文件,然后在最后自动将其重命名为您的文件名。不能从文件中删除行,但只能用所需的行重写。</p>
<blockquote>
<p>if the keyword argument <code>inplace=1</code> is passed to <code>fileinput.input()</code> or to the <code>FileInput</code> constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place.</p>
</blockquote>
<p>里脊</p>
<pre><code>h1,h2,h3
a,b,c
d,e,f
g,h,i
j,k,l
</code></pre>
<p>文件B</p>
<pre><code>h1,h2,h3
a,b,c
1,2,3
g,h,i
4,5,6
</code></pre>
<hr/>
<pre><code>import fileinput, sys, csv
with open('fileB', 'rb') as file_b:
r = csv.reader(file_b)
next(r) #skip header
seen = {(row[0], row[2]) for row in r}
f = fileinput.input('fileA', inplace=True) # sys.stdout is redirected to the file
print next(f), # write header as first line
w = csv.writer(sys.stdout)
for row in csv.reader(f):
if (row[0], row[2]) in seen: # write it if it's in B
w.writerow(row)
</code></pre>
<hr/>
<p>里脊</p>
<pre><code>h1,h2,h3
a,b,c
g,h,i
</code></pre>