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
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"])
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"])
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.
https://qiita.com/ryokurta256/items/defc553f5165c88eac95 Python: open: newline Python: csv: lineterminator
Recommended Posts