简体   繁体   English

如何将标头包含到csv文件中

[英]How to include headers into a csv file

I have a csv file that doesn't include headers. 我有一个不包含标题的csv文件。 How can I manually add the headers ie add the headers to the top of the file 如何手动添加标题,即将标题添加到文件顶部

GA, 11
LA, 12
NY, 122
......

As Lutz Horn pointed out, you can use csv.writeheader if you're using py3.2+. 正如卢茨霍恩指出的那样,你可以使用csv.writeheader如果你使用py3.2 +。 If you're using py2.7 like me, maybe this might help: 如果您像我一样使用py2.7,也许这可能会有所帮助:

import csv
myHeaders = ["Header1", "Header2"]
csvData = []
with open( 'myfile.csv','r+b' ) as csvfile:
    # Read the data
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
    writer = csv.writer(csvfile)
    writer.writerow(myHeaders)
    writer.writerows([row for row in reader])

Note : csv doesn't have an insert/overwrite row method, so you need to read & write the whole data. 注意csv没有插入/覆盖行方法,因此您需要读写整个数据。 Should be trivial for small-to-medium sized files 对于中小型文件应该是微不足道的

Edit: Previous code would append repeated data to the end of the file 编辑:先前的代码会将重复的数据追加到文件的末尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM