2013-01-09 29 views
0

我正在嘗試編寫查看兩個文件的程序,並生成顯示哪些行不同的新文件。兩個文件都行的等量都有無論是數字1或-1每行例如:Python:比較兩個文件並顯示差異的新文件時遇到問題

-1 
1 
1 
-1 

不過到目前爲止,我所做的代碼認爲,每一道線條都是不同的,他們都寫入到新的文件:

f1 = open("file1", "r") 
f2 = open("file2", "r") 

fileOne = f1.readlines() 
fileTwo = f2.readlines() 

f1.close() 
f2.close() 

outFile = open("results.txt", "w") 
x = 0 

for i in fileOne: 
    if i != fileTwo[x]: 
     outFile.write(i+" <> "+fileTwo[x]) 
     print i+" <> "+fileTwo[x] 
    x += 1 

outFile.close() 
+0

[difflib](http://docs.python.org/2/library/difflib.html)是用於查找差異非常方便。 –

回答

4

嘗試這樣:

with open("file1") as f1,open("file2") as f2: 
    for x,y in zip(f1,f2): 
     if x !=y : 
      print " dissimilar lines " 

zip()將獲取兩個文件各行,然後你可以對它們進行比較:

例如:

In [12]: a=[1,2,3] 

In [13]: b=[4,2,6] 

In [14]: for i,(x,y) in enumerate(zip(a,b)): 
    if x !=y : 
     print "line :{0} ==> comparing {1} and {2}".format(i,x,y) 

line :0 ==> comparing 1 and 4 
line :2 ==> comparing 3 and 6 
+0

感謝您的支持!我試過了你的代碼版本,但是我很難找出哪一行是不同的,因爲它只是一遍又一遍地打印「不同的行」。有沒有辦法打印行號? – mrpopo

+0

@mrpopo使用'enumerate()'來查看更新後的示例。 –

相關問題