在CSV Python中写为行的标题 [英] Header written as row in CSV Python
本文介绍了在CSV Python中写为行的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码来创建新行并将其添加到csv文件中.
I have the following code which I am using to create and add a new row to a csv file.
def calcPrice(data):
fieldnames = ["ReferenceID","clientName","Date","From","To","Rate","Price"]
with open('rec2.csv', 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(data)
返回但是,它也作为新行的标题.我该如何预防呢?
return However, it as the header as a new row as well. How can I prevent this?
以下是整个代码的要点链接: https://gist.github.com/chriskinyua/5ff8a527b31451ddc7d7cf157c719bba
Here's a link to the gist with the whole code: https://gist.github.com/chriskinyua/5ff8a527b31451ddc7d7cf157c719bba
推荐答案
您可以检查文件是否已经存在
You could check if the file already exists
import os
def calcPrice(data):
filename = 'rec2.csv'
write_header = not os.path.exists(filename)
fieldnames = ["ReferenceID","clientName","Date","From","To","Rate","Price"]
with open(filename, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if write_header:
writer.writeheader()
writer.writerow(data)
这篇关于在CSV Python中写为行的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文