python csv文件头_Python头文件添加到csv文件

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', 'wb') as outcsv:

writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])

writer.writeheader()

with open('t1.csv', 'rb') as incsv:

reader = csv.reader(incsv)

writer.writerows(row + [0.0] for row in reader)

with open('t2.csv', 'rb') as incsv:

reader = csv.reader(incsv)

writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

解决方案

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', 'wb') as outcsv:

writer = csv.writer(outcsv)

writer.writerow(["Date", "temperature 1", "Temperature 2"])

with open('t1.csv', 'rb') as incsv:

reader = csv.reader(incsv)

writer.writerows(row + [0.0] for row in reader)

with open('t2.csv', 'rb') 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', 'wb') as outcsv:

writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])

writer.writeheader()

with open('t1.csv', 'rb') 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', 'rb') as incsv:

reader = csv.reader(incsv)

writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值