LoginSignup
19
9

More than 3 years have passed since last update.

PythonのCSV出力時に空行が入る現象の回避

Last updated at Posted at 2019-11-02

はじめに

WindowsでPythonからCSVを出力しようとして、一行ごとに空行が入ってしまったので回避策を残す。

出力CSV
a,b,c

d,e,f

g,h,i

環境

  • Windows 10
  • Python 3.7

問題のコード


import csv

with open("./test.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(["a", "b", "c"])
    writer.writerow(["d", "e", "f"])
    writer.writerow(["g", "h", "i"])

解決策

MacとLinuxでなった覚えがないので、Windows環境の問題と考えました。
CRLFが影響していると考えられますので、CRLFを回避する形にしていきます。

  • open関数の引数newlineに空文字列を指定する
  • writer関数の引数lineterminatorに改行コードを指定する

open: newline

行セパレーターの変換先を指定する引数です。
指定していない場合、システムでのデフォルトの改行に変換されます。
Windowsの場合だとCRLFですが、空行が発生してしまうので''\nを指定します。
''か'\n'を指定した場合、変換が行われずそのまま出力される形になります。


import csv

with open("./test.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["a", "b", "c"])
    writer.writerow(["d", "e", "f"])
    writer.writerow(["g", "h", "i"])

writer: lineterminator

各行の終端を表現するための引数です。
デフォルトの場合は\r\nとのことなので、\nを指定します。


with open("./test.csv", "w") as f:
    # writer = csv.writer(f)
    writer = csv.writer(f, lineterminator="\n")
    writer.writerow(["a", "b", "c"])
    writer.writerow(["d", "e", "f"])
    writer.writerow(["g", "h", "i"])

備考

python2.7の場合は、newlineがないのでcsv.writerのlineterminatorを使用する方法になると思います。
io.openならばnewline引数が存在しますが、書き込む文字列がencoding回りで引っ掛かり詳しくは調べていません。

参考

https://qiita.com/ryokurta256/items/defc553f5165c88eac95
Python: open: newline
Python: csv: lineterminator

19
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
9