the first method
Csv file is generated as follows have a plurality of blank lines
import csv
#python2可以用file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile)
#先写入columns_name
writer.writerow(["index","a_name","b_name"])
#写入多行用writerows
writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
Add newline = '' parameters
#coding=utf-8
import csv
#python2可以用file替代open
with open("test.csv","wt",newline='') as csvfile:
writer = csv.writer(csvfile)
#写入多行用writerows
writer.writerows([["index","a_name","b_name"],[0,1,3],[1,2,3],[2,3,4]])
So it will not free the line.
PS: I encountered a problem no one answer? Requires Python learning materials? Click on the link below you can add yourself get
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76
The second method:
First write csv file, and then read out to remove the blank line, and then write
with open('E:\\test.csv','wt')as fout: #生成csv文件,有空行
cout=csv.DictWriter(fout,list_attrs_head )
cout.writeheader()
cout.writerows(list_words)
with open('E:\\test.csv','rt')as fin: #读有空行的csv文件,舍弃空行
lines=''
for line in fin:
if line!='\n':
lines+=line
with open('E:\\test.csv','wt')as fout: #再次文本方式写入,不含空行
fout.write(lines)