mrpopo
mrpopo

Reputation: 1563

Python: Trouble with comparing two files and making a new file which shows the differences

I am trying to write program that looks at two files and makes a new file which shows which lines are different. Both files have an equal amount of lines and both have either the numbers 1 or -1 on each line for example:

-1
1
1
-1

However the code I have made so far thinks that every line is different and writes them all to the new document:

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()

Upvotes: 0

Views: 133

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

try something like this:

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

zip() will fetch individual lines from both files and then you can compare them:

example:

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

Upvotes: 4

Related Questions