python open函数newline参数

python open函数的newline参数控制着如何转换和输出换行符,下面是官方解释:

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

On output, 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.

就是说newline参数只有在文本模式下才起作用,有5个选项:None,'','\n','\r','\r\n'
对于读取:
当newline为None时,会启用通用换行模式,输入中的'\n'(linux系统换行符),'\r'(mac换行符),'\r\n'(windows换行符)都会被转换成'\n'。
当newline为''时,同样会启用通用换行模式,三种换行符都会被当作换行符且原模原样的返回给你,不会被转换。
当newline为5种里面的其他选项时,仅把对应的换行符作为换行符并进行返回。

对于输出:
当newline为None时,所有'\n'会被转换成系统默认的换行符。所以比如windows下写入一行末尾加上'\r\n',实际上会变成'\r\r\n'
当newline为'''\n'时,不进行转换。
当newline为其他选项时,'\n'会被转换成对应的换行符。

你可能感兴趣的:(python open函数newline参数)