Avoiding the phenomenon that blank lines are inserted when outputting Python CSV

Introduction

When I try to output CSV from Python on Windows, a blank line is inserted for each line, so I leave a workaround.

Output CSV


a,b,c

d,e,f

g,h,i

environment

Code in question


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

solution

I don't remember becoming a Mac and Linux, so I thought it was a problem with the Windows environment. It is thought that CRLF has an effect, so we will try to avoid CRLF.

open: newline An argument that specifies the conversion destination of the line separator. If not specified, it will be converted to the system default line feed. In the case of Windows, it is CRLF, but since a blank line will occur, specify '' or \ n. If you specify'' or'\ n', the conversion will not be performed and the output will be as is.


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 An argument to represent the end of each line. The default is \ r \ n, so specify \ 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"])

Remarks

In the case of python2.7, there is no newline, so I think it will be a way to use the lineterminator of csv.writer. If it is io.open, there is a newline argument, but the character string to be written is caught around encoding and I have not investigated it in detail.

reference

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

Recommended Posts

Avoiding the phenomenon that blank lines are inserted when outputting Python CSV
Import modules that are often used when starting the python interpreter
Are Php / Ruby / Python that only runs when the file is called directly
[Python] Solution to the problem that elements are linked when copying a list
[Python: UnicodeDecodeError] One of the error solutions when reading CSV
Solve the Japanese problem when using the CSV module in Python.
Verification of the theory that "Python and Swift are quite similar"