You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python脚本匹配两个TXT文件键值对、校验并导出结果

实现代码及说明

核心实现思路

  • 先实现通用的键值文件读取校验函数:读取文件时逐行解析,同步校验重复键、空键、空值,返回解析后的字典和校验错误列表
  • 读取两个文件后,取键的交集,按照要求的字段导出为csv文件(无需额外依赖,若需导出xls可修改导出逻辑引入openpyxl库即可)
  • 校验结果会统一输出,可直接定位文件里的异常行

完整可运行代码

def load_kv_file(file_path):
    kv_dict = {}
    errors = []
    with open(file_path, 'r', encoding='utf-8') as f:
        # 逐行读取,行号从1开始计数方便定位问题
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            # 跳过空行
            if not line:
                continue
            # 只拆分第一个等号,避免值中包含等号导致解析错误
            parts = line.split('=', 1)
            if len(parts) < 2:
                errors.append(f"行{line_num}:格式错误,缺少=分隔符,内容为{line}")
                continue
            key = parts[0].strip()
            value = parts[1].strip()
            if not key:
                errors.append(f"行{line_num}:存在空键")
                continue
            if not value:
                errors.append(f"行{line_num}:键{key}对应值为空")
                continue
            if key in kv_dict:
                errors.append(f"行{line_num}:键{key}重复,首次出现位置为行{kv_dict[key][1]}")
                continue
            kv_dict[key] = (value, line_num)
    # 返回处理好的键值对字典、错误信息列表
    return {k:v[0] for k,v in kv_dict.items()}, errors


if __name__ == "__main__":
    # 可根据实际文件路径修改以下配置
    file1_path = "File1.txt"
    file2_path = "File2.txt"
    output_csv_path = "compare_result.csv"

    # 读取并校验两个文件
    file1_dict, file1_errors = load_kv_file(file1_path)
    file2_dict, file2_errors = load_kv_file(file2_path)

    # 打印校验结果
    print("===== File1.txt 校验结果 =====")
    if file1_errors:
        for err in file1_errors:
            print(err)
    else:
        print(f"无异常,共读取有效键值对{len(file1_dict)}个")
    
    print("\n===== File2.txt 校验结果 =====")
    if file2_errors:
        for err in file2_errors:
            print(err)
    else:
        print(f"无异常,共读取有效键值对{len(file2_dict)}个")
    
    # 取两个文件共有的键
    common_keys = set(file1_dict.keys()) & set(file2_dict.keys())
    print(f"\n===== 两个文件共有的键数量:{len(common_keys)} =====")

    # 导出比对结果到csv
    if common_keys:
        import csv
        # 用utf-8-sig编码避免Excel打开乱码
        with open(output_csv_path, 'w', encoding='utf-8-sig', newline='') as csvf:
            writer = csv.writer(csvf)
            # 写入表头
            writer.writerow(["键", "File1对应值", "File2对应值"])
            # 按字典序排序后写入内容
            for key in sorted(common_keys):
                writer.writerow([key, file1_dict[key], file2_dict[key]])
        print(f"比对结果已导出到{output_csv_path}")

补充说明

  • 如果你的文件是GBK编码,把open函数里的encoding='utf-8'改成encoding='gbk'即可
  • 若需要导出xls/xlsx格式,先安装openpyxl库,再把导出csv的逻辑替换为以下代码即可:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["键", "File1对应值", "File2对应值"])
for key in sorted(common_keys):
    ws.append([key, file1_dict[key], file2_dict[key]])
wb.save("compare_result.xlsx")

内容的提问来源于stack exchange,提问作者Nilesh122n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:45:05