我有两个文件,file1包含内容为
aaa
bbb
ccc
和文件2包含内容
ccc 2
ddd 10
eee 11
aaa 12
rrr 3
bbb 20
nnn 46
我想这样做,如果file2包含file1的行,那么该行将从file2中删除。最后,file2将为
ddd 10
eee 11
rrr 3
nnn 46
此外,我的代码是
f1 = open("test1.txt","r")
f2 = open("test2.txt","r")
fileOne = f1.readlines()
fileTwo = f2.readlines()
f1.close()
f2.close()
outFile = open("test.txt","w")
x = 0
for i in fileOne:
if i != fileTwo[x]:
outFile.writelines(fileTwo[x])
x += 1
outFile.close()
谢谢。
答案 0 :(得分:3)
set
最好:
with open(file1) as f1:
s = set(x.strip() for x in f1)
with open(file2) as f2, open(fileout,'w') as fout:
for line in f2:
if line.split(None,1)[0] not in s:
fout.write(line)
答案 1 :(得分:0)