文件内容差异对比

在运维过程中,难免需要对比不同时间段修改的配置文件来确定一个服务到底修改了那些内容,最新一次变动还需要改动那些内容。而python3中的difflib模块则有十分强大的文件差异对比的功能,其中的HtmlDiff()方法可以生成已经对比好的html文件,方便我们进行阅读。

脚本设计流程:

下面就贴上脚本的源代码:

import difflib
import sys
try:
    textfile1 = input("Please input your config file1>>:")
    textfile2 = input("Please input your config file2>>:")
except Exception as e:
    print("Error" + str(e))
    sys.exit()

def readfile(filename):
    try:
        file_obj = open(filename, 'r')
        text = file_obj.read().splitlines()
        file_obj.close()
        return text
    except IOError as e:
        print("Error" + str(e))
        sys.exit()

def make_html_file(filename1, filename2):
    try:
        diff_obj = difflib.HtmlDiff()
        html_context = diff_obj.make_file(filename1, filename2)
        return html_context
    except Exception as e:
        print("Error" + str(e))
        sys.exit()
def save_html_file(context, file_path):
    try:
        file_obj = open(file_path, 'w')
        for line in context:
            file_obj.write(line)
        file_obj.close()
    except IOError as e:
        print("IOError" + str(e))
        sys.exit()

if __name__ == '__main__':
    if textfile1 == "" or textfile2 == "":
       print ("Please check your input")
        sys.exit()
    text1_context = readfile(textfile1)
    text2_context = readfile(textfile2)
    html_context = make_html_file(text1_context, text2_context)
    save_file_path = input("Please input your html file save path>>>:")
    save_html_file(html_context, save_file_path)
    print("Successful!!!")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值