使用itertools.ifilter
(或在Python 3只正常filter
)
itertools.ifilter(predicate, iterable)
你的谓语应该是一个函数,要忽略行返回False
。 例如。
def predicate(line):
if 'something' in line:
return False # ignore it
return True
然后在你的文件对象上使用它。 fin = ifilter(predicate, fin)
然后,只需使用类似
from itertools import izip, ifilter # on Py3 instead use normal zip and filter
f1 = ifilter(predicate, f1)
f2 = ifilter(predicate, f2)
all(x == y for x, y in izip(f1, f2))
,除非你想看到什么差异,既然你已经尝试filcmp
我以为你只是想知道是否有区别你不需要difflib
或不。不幸的是,filecmp
只适用于文件名。
而且跳过每个文件的第一行只是用itertools.islice(fin, 1, None)
from itertools import islice, izip
def predicate(line):
''' you can add other general checks in here '''
if line.startswith('Date'):
return False # ignore it
return True
with open('File1.txt') as f1, open('File2.txt') as f2:
f1 = ifilter(predicate, f1)
f2 = ifilter(predicate, f2)
print(all(x == y for x, y in izip(f1, f2)))
>>> True
我试过这个,但是我收到错误。如果我做错了,你能纠正我吗?>>> fo1 = open(“file1.txt”,“r”) >>> fo2 = open(“file2。(x),y(x),y(x,y)), izip(F1,F2)) 回溯(最近通话最后一个): 文件 “”,1号线,在 文件 “”,1号线,在 类型错误: '海峡' 对象没有callable' –
sarbjit
2013-04-29 10:44:24
@sarbjit'predicate'应该是一个函数,我更新了我的答案以显示一个示例。 – jamylak 2013-04-29 10:46:06
非常好!!感谢您的帮助 – sarbjit 2013-04-29 10:52:36