Reputation: 109
Can someone tell me the difference between lineterminator='\n'
and newline=''
in the 2 instances below?
1:
data=[person,age]
with open(document.csv, 'a') as file:
writing = csv.writer(file, lineterminator='\n')
wr.writerow(data)
2:
data=[person,age]
with open(document.csv, 'a', newline='') as file:
writing = csv.writer(file)
wr.writerow(data)
When viewing the csv file, both result in the same output...
Upvotes: 0
Views: 95
Reputation: 1123620
The two options do not produce the same file output on Linux or Mac. Only on Windows will you see the same output.
The first instructs the csv
module to write \n
as the line terminator between lines. The file object it is writing to, being in text mode, will then translate that terminator to the platform default. The default is \n
on Linux or Mac, but it is \r\n
on Windows.
The second piece instructs the file object to not change the line endings being written to it (it would otherwise translate line separators). The csv
module is left to the default, so it'll write two \r\n
characters between lines. The result is that all lines are terminated with \r\n
regardless of the platform.
See the Dialect.lineterminator
documentation:
The string used to terminate lines produced by the
writer
. It defaults to'\r\n'
.
and the open()
documentation:
When writing output to the stream, if newline is None, any
'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
or'\n'
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
Upvotes: 5