我正在寻找一种比较两个文件file1和file2的pythonic方法,以补丁文件的形式获取差异并将其差异合并到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来找到差异,但是我正在寻找创建和应用补丁的解决方案。

最佳答案

首先,您需要安装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)

08-26 16:19