[Python] Pythonically add header to a csv file

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote a Python script merging two csv files, and now I want to add a header to the final csv. I tried following the suggestions reported here and I got the following error: expected string, float found. What is the most pythonic way to fix this?

    Here is the code I am using:

    import csv

    with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
    reader = csv.reader(incsv)
    writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
    reader = csv.reader(incsv)
    writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

    Continue reading...

Compartilhe esta Página