使用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