Python中通過csv的writerow輸出的內容有多余的空行兩種方法


第一種方法

如下生成的csv文件會有多個空行

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]])

加入newline='' 參數

#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]])

這樣就不會有空行了。

PS:遇到問題沒人解答?需要Python學習資料?可以加點擊下方鏈接自行獲取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

第二種方法:

先寫入csv文件,然后讀出去掉空行,再寫入

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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM