Python 如何比较两个文件';没有数字的字符串
我有两个文件,file1包含如下内容Python 如何比较两个文件';没有数字的字符串,python,string,Python,String,我有两个文件,file1包含如下内容 aaa bbb ccc ccc 2 ddd 10 eee 11 aaa 12 rrr 3 bbb 20 nnn 46 文件2包含如下内容: aaa bbb ccc 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
aaa
bbb
ccc
ccc 2
ddd 10
eee 11
aaa 12
rrr 3
bbb 20
nnn 46
文件2包含如下内容:
aaa
bbb
ccc
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()
谢谢。假设您的代码正常工作,只需更换:
if i != fileTwo[x]
借
您也可以使用假设代码正常工作,只需替换:
if i != fileTwo[x]
借
您也可以使用A
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)
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)
您想在Python中执行此操作吗?如果您的代码无法工作,请解释错误的性质。如果是,为什么会出现在这里?假设两个文件都已排序。是否要使用Python进行排序?如果代码无法正常工作,请解释错误的性质。如果是,你为什么在这里?你假设两个文件都已排序。