0

我正在尝试编写查看两个文件并创建一个新文件以显示哪些行不同的程序。两个文件都有相同数量的行,并且每行都有数字 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()
4

1 回答 1

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
于 2013-01-09T23:25:16.387 回答