【Python】文本内容比较小工具

本文介绍了如何使用Python编写一个脚本来比较在数据库迁移后两个文件(如MySQL和Oracle)的记录是否相同,通过读取文件并计算hash值进行对比,提供了一个实际的代码示例和使用方法。
摘要由CSDN通过智能技术生成

概要

在做数据库迁移的时候通过Python编写了一个比较不同数据库的记录是否相同的小工具,把它分享给大家,希望会对大家有所帮助。

问题场景

由于项目需要把数据库从mysql换成oracle,在做完数据迁移之后需要比较迁移的数据是否相同,我们采用的是通过hash值比较数据是否相同,于是我们就编写了一个Python脚本,用来比较不同数据库生成的hash值是否相同。

相关代码

import argparse


def data_compare(file_path1, file_path2, result_path):
    try:
        # 清空文件内容
        with open(result_path, 'w') as result_file:
            result_file.write('数据比较结果:')
            result_file.write('\r\n')

        with open(file_path1, 'r') as file1:
            lines_in_file1 = file1.readlines()

        with open(file_path2, 'r') as file2:
            lines_in_file2 = file2.readlines()

        if len(lines_in_file1) != len(lines_in_file2):
            with open(result_path, 'a') as result_file:
                print('文件内容的行数不同,请检查。')
                result_file.write('\t')
                result_file.write('文件内容的行数不同,请检查。')
                result_file.write('\r\n')
                return

        all_same = True
        define_header = False

        for index, value1 in enumerate(lines_in_file1):
            value2 = lines_in_file2[index]
            if value1 != value2:
                with open(result_path, 'a') as result_file:
                    if not define_header:
                        result_file.write('\t')
                        result_file.write('下面这些是不同的记录:')
                        result_file.write('\r\n')
                        define_header = True

                    result_file.write('\t')
                    result_file.write('行数: ' + str(index) + '; ')
                    result_file.write('值1: ' + value1.replace("\n", "") + '; ')
                    result_file.write('值2: ' + value2.replace("\n", ""))
                    result_file.write('\r\n')
                if all_same:
                    all_same = False

        if not all_same:
            print('存在不同的数据,请检查保存结果的文件。')
        else:
            with open(result_path, 'a') as result_file:
                print('所有数据都相同。')
                result_file.write('\t')
                result_file.write('所有数据都相同。')

    except Exception as e:
        print("数据比较失败:", e)


# 创建命令行参数
parser = argparse.ArgumentParser(description="比较输入的不同文件中的数据")
parser.add_argument("--file_path1", help="文件1的路径")
parser.add_argument("--file_path2", help="文件2的路径")
parser.add_argument("--result_path", help="保存比较结果的文件路径")

# 解析参数
args = parser.parse_args()

# 调用方法
data_compare(args.file_path1, args.file_path2, args.result_path)

使用方式

假设保存文件为data_compare.py。
在命令行执行如下命令:

python data_compare.py --file_path1 文件1路径 --file_path2 文件2路径 --result_path 保存结果的文件路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值