如何比较没有数字的两个文件的字符串

时间:2013-06-03 15:40:50

标签: python string

我有两个文件,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()

谢谢。

2 个答案:

答案 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)

假设您的代码正常运行,只需替换:

if i !=  fileTwo[x]

通过

if not i in fileTwo[x]

您也可以使用startswith()