我试图找到一种从其他文件中写入CSV文件的方法。 第一行是标题,必须不带引号。 所有其他行必须带引号。
我尝试使用DictWriter获取标题并写入所有行,但仍引用所有行(带标题)。
这是我写的一个例子:
writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self), delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONNUMERIC)
writer.writeheader()
输出文件应如下所示:
column1,column2,column3
"1111","2222","3333"
答案 0 :(得分:2)
A simple way would be to use 2 different csv writers on the same file object:
writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self),
delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONE)
writer.writeheader()
writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self),
delimiter=',', quotechar='\"', quoting=csv.QUOTE_ALL)
# actually write the data to writer
答案 1 :(得分:1)
我认为您可以在编写标题后将writer
的定义从quoting=csv.QUOTE_NONE
更改为quoting=csv.QUOTE_ALL
。
import csv
with open('eggs2.csv','w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_NONE)
spamwriter.writerow(['column1','column2','column3','column...'])
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_ALL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
spamwriter.writerow([1111, 2222, 33333])
结果:
column1,column2,column3,column...
"Spam","Spam","Spam","Spam","Spam","Baked Beans"
"Spam","Lovely Spam","Wonderful Spam"
"1111","2222","33333"