The DictWriter()
class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer()
and pass in a simple row for the header:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])
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)
The alternative would be to generate dictionaries when copying across your data:
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({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…