签到成功

知道了

CNDBA社区CNDBA社区

Python对比两文件

2021-10-03 19:09 928 0 原创 Python
作者: hbhe0316

Company.py文件

http://www.cndba.cn/hbhe0316/article/4858
http://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858

#!/bin/env python
# -*- coding: utf-8 -*-

# 20200622

#python db2Compare.py -f1 db01.db2chk.200622.out -f2 db02.db2chk.200622.out

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)

python Company.py -f1 db01.db2chk.200622.out -f2 db02.db2chk.200622.outhttp://www.cndba.cn/hbhe0316/article/4858http://www.cndba.cn/hbhe0316/article/4858

http://www.cndba.cn/hbhe0316/article/4858

版权声明:本文为博主原创文章,未经博主允许不得转载。

Python

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
hbhe0316

hbhe0316

关注

1.只有承认无知,才能装下新的东西; 2.进步来自一点点滴滴的积累; 3.广博让你更优秀,而专业让你无法替代; 4.挫折和失败能够转换为一种财富。

  • 889
    原创
  • 1
    翻译
  • 13
    转载
  • 24
    评论
  • 访问:1147420次
  • 积分:1523
  • 等级:核心会员
  • 排名:第6名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ