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



