difflib模块提供的类和方法用来进行序列的差异化比较,它能够比对文件并生成差异结果文本或者html格式的差异化比较页面,如果需要比较目录的不同,可以使用filecmp模块
1 difflib.Differ
此类比较的是文本行的差异并且产生适合人类阅读的差异结果或者增量结果,结果中各部分的表示如下
import sys import difflib def read_file(filename): try: with open(filename, 'r', encoding='UTF-8') as f: return f.readlines() except IOError: print("ERROR: 没有找到文件:%s或读取文件失败!" % filename) sys.exit(1) def compare_file(file1, file2): file1_content = read_file(file1) file2_content = read_file(file2) d = difflib.Differ() diff = d.compare(file1_content, file2_content) return ''.join(diff) ret = compare_file(r'D: est_prostaticspringboot-saoleimastersrcmainjavacomexamplecontrollerIndex.java',r'D: est_prostaticspringboot-saolei estsrcmainjavacomexamplecontrollerIndex.java')
+ System.out.println("修改了当前方法"); return "index"; } + // 下面删除了一个方法 - - @Autowired - private TestBean tb; - - @SecurityIgnoreHandler - @RequestMapping("/single") - @ResponseBody - - public String single() {
2 difflib.HtmlDiff
此类可以被用来创建HTML表格 (或者说包含表格的html文件) ,两边对应展示或者行对行的展示比对差异结果。
import sys import difflib def read_file(filename): try: with open(filename, 'r', encoding='UTF-8') as f: return f.readlines() except IOError: print("ERROR: 没有找到文件:%s或读取文件失败!" % filename) sys.exit(1) def compare_file(file1, file2, out_file): file1_content = read_file(file1) file2_content = read_file(file2)
d = difflib.HtmlDiff() result = d.make_file(file1_content, file2_content) with open(out_file, 'w',encoding='utf-8') as f: f.writelines(result) content_html = compare_file(r'路劲1',r'路劲2',r'输出路劲.html')
还有好多种方法 待更新