Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonically add header to a csv file

Tags:

python

csv

header

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) 
like image 965
albus_c Avatar asked Dec 03 '13 09:12

albus_c


People also ask

How do I add a heading to a CSV file in Python?

In this article, we are going to add a header to a CSV file in Python. Method #1: Using header argument in to_csv() method. Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.

Can CSV files have headers?

From those guidelines and giving the lack of standardization, the header line is optional in a CSV file. When present, the header line must be the first line in the file and must contain the same number of fields as the records. Header and records lines must use the same field delimiters.


1 Answers

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) 
like image 72
Martijn Pieters Avatar answered Sep 28 '22 10:09

Martijn Pieters