如何使用python diff_match_patch创建补丁并应用它

时间:2016-10-18 05:33:09

标签: python python-3.x merge match diff

我正在寻找一种pythonic方法来比较两个文件file1和file2获取补丁文件形式的差异,并将它们的差异合并到file2中。代码应该是这样的:

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

我在google的python API dif_match_patch上看过以下帖子Implementing Google's DiffMatchPatch API for Python 2/3以找出差异,但我正在寻找创建和应用补丁的解决方案。

1 个答案:

答案 0 :(得分:3)

首先,您需要安装diff_match_patch

这是我的代码:



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)