2015-06-18 57 views
0

我想从两个文件发现差别,但我依然从两个文件寻找差异不工作

得到答案这是我的代码

#File one(This file contents should be removed after comparing file two) 
a = open('diff1','r+') 
#File two 
#This file has 999999 records 
b = open('gtin','r+') 
f8 = open('missing-test-remove.txt','w') 
def diff(a, b): 
    c = set(a).union(set(b)) 
    d = set(a).intersection(set(b)) 
    result = list(c - d) 
    for s in result: 
     print s 
     f8.write(s) 

diff(a,b) 

但我依然从两个文件获得相同的结果,但文件内容,一个均应使用文件比较两个

+0

请在处理文件时使用上下文管理。 ''open'('diff1')as:'... –

+0

你只是想在比较两个文件并删除从'File one'重复的元素之后再写一个新列表? –

+0

您可能会发现使用标准库中的'filecmp'更简单https://docs.python.org/2/library/filecmp.html – cdarke

回答

1

你做错了什么是后去除 -

c = set(a).union(set(b)) 
d = set(a).intersection(set(b)) 

请注意ab仍然是文件描述符,一旦你做了set(a),如果你再次做set(a),你将得到一个空集,因为在第一次调用set(a)时,完整的文件已经被读取,而光标为文件在最后。

您需要更改您的代码,以便您只拨打set(a)和`set(b)一次。沿着线的东西 -

#File one(This file contents should be removed after comparing file two) 
a = open('diff1','r+') 
#File two 
#This file has 999999 records 
b = open('gtin','r+') 
f8 = open('missing-test-remove.txt','w') 
def diff(a, b): 
    sa = set(a) 
    sb = set(b) 
    c = sa.union(sb) 
    d = sa.intersection(sb) 
    result = list(c - d) 
    for s in result: 
     print s 
     f8.write(s) 

diff(a,b) 

此外,您应该刷新文件到你写,完成写入后,并在年底关闭所有的文件 -

a.close() 
b.close() 
f8.close() 
0

您需要保存设定值。一个简单的测试:

print a 
    print set(a) 
    print a 
    print set(a) # wrong 

所以

seta = set(a) 
    setb = set(b) 
    setc = seta.union(setb) 
    setd = seta.intersection(setb)