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

Python处理CSV时-----END CERTIFICATE-----前多换行问题求助

问题解决:CSV处理中证书END标记前多余空行的修复

问题根源分析

你的代码存在两个核心问题导致多余空行出现:

  1. 拼接证书/公钥时末尾多写了\n'(多余的单引号和换行),造成格式异常
  2. 直接使用replace移除标记的方式不够精准,可能残留标记前后的空白换行

修正后的代码

import csv
import os

# 定义输入输出文件
input_files = ['11296205_124_2025.csv', '11296208_113_2025.csv']
output_file = 'inventory_upload.csv'

converted_data = []

# 处理每个输入文件
for input_file in input_files:
    if not os.path.exists(input_file):
        print(f"Warning: {input_file} not found, skipping.")
        continue
    
    with open(input_file, mode='r', encoding='utf-8') as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            # 提取并清理原始证书和公钥
            tpm_certificate = row['TPM Certificate'].strip()
            gek_public_key = row['GEK Public Key'].strip()
            
            # 精准提取证书主体内容并格式化
            if '-----BEGIN CERTIFICATE-----' in tpm_certificate and '-----END CERTIFICATE-----' in tpm_certificate:
                cert_body = tpm_certificate.split('-----BEGIN CERTIFICATE-----')[1].split('-----END CERTIFICATE-----')[0].strip()
                # 移除空行并规整每行格式
                cert_body = '\n'.join([line.strip() for line in cert_body.splitlines() if line.strip()])
                tpm_certificate = f"-----BEGIN CERTIFICATE-----\n{cert_body}\n-----END CERTIFICATE-----"
            
            # 同样处理公钥
            if '-----BEGIN PUBLIC KEY-----' in gek_public_key and '-----END PUBLIC KEY-----' in gek_public_key:
                key_body = gek_public_key.split('-----BEGIN PUBLIC KEY-----')[1].split('-----END PUBLIC KEY-----')[0].strip()
                key_body = '\n'.join([line.strip() for line in key_body.splitlines() if line.strip()])
                gek_public_key = f"-----BEGIN PUBLIC KEY-----\n{key_body}\n-----END PUBLIC KEY-----"

            # 组装处理后的数据
            converted_data.append([
                row['Hardware Model'].strip(),
                row['Hardware Serial Number'].strip(),
                tpm_certificate,
                gek_public_key,
                ""  # 空UUID字段
            ])

# 写入输出文件,确保带换行的内容被正确引用
with open(output_file, mode='w', encoding='utf-8', newline='') as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_ALL)
    writer.writerow(["Model", "Serial", "EK Certificate", "GEK Public Key", "UUID"])
    writer.writerows(converted_data)

print(f"File converted and saved as {output_file}")

关键修复点说明

  1. 精准提取内容:改用split方法分割BEGIN/END标记,直接提取中间主体内容,避免replace操作可能残留的空白
  2. 移除多余字符:删除拼接时末尾多余的\n',确保格式为BEGIN\n内容\nEND,保证END标记前仅有一个换行
  3. 优化CSV引用:将quoting=csv.QUOTE_MINIMAL改为csv.QUOTE_ALL,确保包含换行的证书/密钥内容被正确包裹,避免CSV格式混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:12:01