[英]Python: Trouble with comparing two files and making a new file which shows the differences
我正在嘗試編寫一個程序,該程序查看兩個文件並制作一個新文件,以顯示哪些行不同。 這兩個文件的行數相等,並且每行的數字都為1或-1,例如:
-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()
嘗試這樣的事情:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.