1,105,594 Community Members

How to compare two files and save difference in thrid file

Member Avatar
sreelatha
Newbie Poster
4 posts since Apr 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

I have a requirement that i have two files, one is input file and another is log file(both will contain the same data mostly). I need to compare these two files and if any difference found then those lines should be write to another file(3rd file).

I done googling, but I am able to find only two files comparison which returns true or false.

Has any one have idea? please help me.

thx & rgds,
sreelatha

Member Avatar
Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 299 [?]
Q&As Helped to Solve: 119 [?]
Skill Endorsements: 0 [?]
 
0
 

Simple read the use file.readlines() on both files to give you 2 arrays

so something like this

f1 = open("file1.txt", "r")
f2 = open("file2.txt", "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])
   x += 1

outFile.close()

something along those lines

Chris

Member Avatar
kdoiron
Light Poster
37 posts since May 2008
Reputation Points: 29 [?]
Q&As Helped to Solve: 8 [?]
Skill Endorsements: 0 [?]
 
0
 

Of course, you'll have to do it the other way too - to look through file2 to be sure everything there is also in file1.

Member Avatar
woooee
Posting Maven
2,798 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

We had a topic like this a short while ago. The easiest/most efficient method is to use two sets and compare with set1.difference(set_2) and vice-versa. Also, python has difflib which may or may not be more than you want. http://docs.python.org/lib/differ-examples.html

Member Avatar
sreelatha
Newbie Poster
4 posts since Apr 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi guys,

Thanks for your reply. It helped me a lot

Question Answered as of 4 Years Ago by woooee, Freaky_Chris and kdoiron
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article