该解决方案使用fileinput
withinplace=True
,它会写入一个临时文件,然后在最后自动将其重命名为您的文件名。您无法从文件中 删除 行,但只能用所需的行重写它。
如果将关键字参数inplace=1
传递给构造函数fileinput.input()
或将其传递给FileInput
构造函数,则该文件将移动到备份文件,并且标准输出将定向到输入文件(如果已经存在与备份文件同名的文件,它将被无提示替换) 。这样就可以编写一个过滤器,该过滤器可以在适当位置重写其输入文件。
文件A
h1,h2,h3
a,b,c
d,e,f
g,h,i
j,k,l
文件B
h1,h2,h3
a,b,c
1,2,3
g,h,i
4,5,6
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)
文件A
h1,h2,h3
a,b,c
g,h,i