Python 这两行有什么区别?

Python whats the difference between these 2 lines?

谁能告诉我下面两个实例中lineterminator='\n'newline=''的区别?

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)

查看 csv 文件时,两者的输出相同...

这两个选项 不会 在 Linux 或 Mac 上产生相同的文件输出。只有在 Windows 上你才会看到相同的输出。

第一个指示csv模块写入\n作为行与行之间的行终止符。它正在写入的文件对象处于文本模式,然后将该终止符转换为平台默认值。 Linux 或 Mac 上的默认值为 \n,但 Windows 上的默认值为 \r\n

第二部分指示 文件对象 不要更改写入它的行结尾(否则它会转换行分隔符)。 csv 模块保留为默认值,因此它会在行之间写入两个 \r\n 字符。结果是无论平台如何,所有行都以 \r\n 终止。

参见 Dialect.lineterminator documentation:

The string used to terminate lines produced by the writer. It defaults to '\r\n'.

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.