为CSV文件添加标题吗? [英] Append a Header for CSV file?

查看:527
本文介绍了为CSV文件添加标题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将标头添加到我的CSV文件中.

I am trying to add a header to my CSV file.

我正在从.csv文件中导入数据,该文件具有两列数据,每列包含浮点数.示例:

I am importing data from a .csv file which has two columns of data, each containing float numbers. Example:

  11   22
  33   44
  55   66

现在,我想为两列添加标题:

Now I want to add a header for both columns like:

 ColA  ColB
  11    22
  33    44
  55    66

我已经尝试过:

with open('mycsvfile.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(('ColA', 'ColB'))

我使用了'a'来追加数据,但这将值添加到了文件的底部而不是第一行.有什么办法可以解决?

I used 'a' to append the data, but this added the values in the bottom row of the file instead of the first row. Is there any way I can fix it?

推荐答案

一种方法是读入所有数据,然后用标头覆盖文件,然后再次写出数据.对于大型CSV文件,这可能不切实际:

One way is to read all the data in, then overwrite the file with the header and write the data out again. This might not be practical with a large CSV file:

#!python3
import csv
with open('file.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('file.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['ColA','ColB'])
    w.writerows(data)

这篇关于为CSV文件添加标题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆