[Python] Extra newline before -----END CERTIFICATE----- when processing CSV in Python

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm processing CSV files in Python to extract and format data from another file. However, when writing the output, I get an extra newline before -----END CERTIFICATE-----. I want the output to have print one newline before -----END CERTIFICATE-----, but my current code adds an extra blank line its like its escaping it and i don't understand why

    i tried using.strip() on the certificate and public key to remove any leading or trailing whitespace, but the extra newline still appeared.

    The begin certificate part is correct with -----BEGIN CERTIFICATE----- \n but the ending isnt

    Any advice on how to correct this?

    import csv
    import os

    # Define input files and output file
    input_files = ['11296205_124_2025.csv', '11296208_113_2025.csv']
    output_file = 'inventory_upload.csv'

    # Prepare the output data list
    converted_data = []

    # Process each input file
    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:
    # Get the certificate and key values
    tpm_certificate = row['TPM Certificate'].strip()
    gek_public_key = row['GEK Public Key'].strip()

    # Remove existing markers and normalize newlines
    tpm_certificate = tpm_certificate.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "")
    gek_public_key = gek_public_key.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "")

    # Ensure there are no extra empty lines
    tpm_certificate = "\n".join([line.strip() for line in tpm_certificate.splitlines() if line.strip()])
    gek_public_key = "\n".join([line.strip() for line in gek_public_key.splitlines() if line.strip()])

    # Correctly format the certificate without extra newlines
    tpm_certificate = f"-----BEGIN CERTIFICATE-----\n{tpm_certificate}\n-----END CERTIFICATE-----\n'"
    gek_public_key = f"-----BEGIN PUBLIC KEY-----\n{gek_public_key}\n-----END PUBLIC KEY-----\n'"

    # Append processed data
    converted_data.append([
    row['Hardware Model'].strip(),
    row['Hardware Serial Number'].strip(),
    tpm_certificate,
    gek_public_key,
    "" # Empty UUID field
    ])

    # Write the combined output file
    with open(output_file, mode='w', encoding='utf-8', newline='') as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL)
    # Write the header
    writer.writerow(["Model", "Serial", "EK Certificate", "GEK Public Key", "UUID"])
    # Write the processed data
    writer.writerows(converted_data)

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

    Continue reading...

Compartilhe esta Página