Pythonでcsvのwriterowで出力されるコンテンツには余分な空行の2つの方法があります

1340 ワード

第一の方法
次のように生成される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
2つ目の方法:
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!='
': lines+=line with open('E:\\test.csv','wt')as fout: # , fout.write(lines)