• 比较两个文件的异同Python3 标准库difflib 实现


    比较两个文件的异同Python3 标准库difflib 实现

    对于要比较两个文件特别是配置文件的差异,这种需求很常见,如果用眼睛看,真是眼睛疼。
    可以使用linux命令行工具diff a_file b_file,但是输出的结果读起来不是很友好。这时候使用python的标准库difflib就能满足我们的需求。

    下面这个脚本使用了difflib和argparse,argparse用于解析我们给此脚本传入的两个参数(即两份待比较的文件),由difflib执行比较,比较的结果放到了一个html里面,只要找个浏览器打开此html文件,就能直观地看到比较结果,两份文件有差异的地方会高亮显示出来。

    废话少说,直接上代码:

    # _*_ coding: utf-8 _*_
    
    import difflib
    import sys
    import argparse
    
    
    # 读取建表语句或配置文件
    def read_file(file_name):
        try:
            file_desc = open(file_name, 'r')
            # 读取后按行分割
            text = file_desc.read().splitlines()
            file_desc.close()
            return text
        except IOError as error:
            print('Read input file Error: {0}'.format(error))
            sys.exit()
    
    
    # 比较两个文件并把结果生成一份html文本
    def compare_file(file1, file2):
        if file1 == "" or file2 == "":
            print('文件路径不能为空:第一个文件的路径:{0}, 第二个文件的路径:{1} .'.format(file1, file2))
            sys.exit()
        else:
            print("正在比较文件{0} 和 {1}".format(file1, file2))
        text1_lines = read_file(file1)
        text2_lines = read_file(file2)
        diff = difflib.HtmlDiff()    # 创建HtmlDiff 对象
        result = diff.make_file(text1_lines, text2_lines)  # 通过make_file 方法输出 html 格式的对比结果
        # 将结果写入到result_comparation.html文件中
        try:
            with open('result_comparation.html', 'w') as result_file:
                result_file.write(result)
                print("0============> Successfully Finished\n")
        except IOError as error:
            print('写入html文件错误:{0}'.format(error))
    
    
    if __name__ == "__main__":
        # To define two arguments should be passed in, and usage: -f1 fname1 -f2 fname2
        my_parser = argparse.ArgumentParser(description="传入两个文件参数")
        my_parser.add_argument('-f1', action='store', dest='fname1', required=True)
        my_parser.add_argument('-f2', action='store', dest='fname2', required=True)
        # retrieve all input arguments
        given_args = my_parser.parse_args()
        file1 = given_args.fname1
        file2 = given_args.fname2
        compare_file(file1, file2)
    

    在CMD 中运行及结果如下图:

  • 相关阅读:
    寄存器总结
    汇编知识积累
    windbg 配置符号路径
    UNICODE环境下读写txt文件操作
    vs2010 安装项目完成桌面快捷方式无法定位程序文件夹 解决方法
    spring源码解析之属性编辑器propertyEditor
    springboot国际化与@valid国际化支持
    No identifier specified for entity
    springboot 项目中css js 等静态资源无法访问的问题
    Git教程
  • 原文地址:https://www.cnblogs.com/michaelcjl/p/11716310.html
Copyright © 2020-2023  润新知