3

I'm looking for a pythonic way to compare two files file1 and file2 obtain the differences in form of a patch file and merge their differences into file2. The code should do something like this:

diff file1 file2 > diff.patch
apply the patch diff.patch to file2 // this must be doing something like git apply.

I have seen the following post Implementing Google's DiffMatchPatch API for Python 2/3 on google's python API dif_match_patch to find the differences but I'm looking for a solution to create and apply patch.

1 Answer 1

3

First you need to install diff_match_patch.

Here is my code:

import sys
import time
import diff_match_patch as dmp_module


def readFileToText(filePath):
	file = open(filePath,"r")
	s = ''
	for line in file:
    		s = s + line
	return s
    

dmp = dmp_module.diff_match_patch()
origin = sys.argv[1];
lastest = sys.argv[2];

originText = readFileToText(origin)
lastestText = readFileToText(lastest)

patch = dmp.patch_make(originText, lastestText)
patchText = dmp.patch_toText(patch)

# floder = sys.argv[1]
floder = '/Users/test/Documents/patch'
print(floder)
patchFilePath = floder
patchFile = open(patchFilePath,"w")
patchFile.write(patchText)

print(patchText)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.