美文网首页
python open函数newline参数

python open函数newline参数

作者: WuYankang | 来源:发表于2022-06-14 15:41 被阅读0次

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参数

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

  • python open函数newline用法

    写这些文章主要是督促自己学习,过去两年时间,断断续续在学习linux、python以及机器学习方面的知识,东西看了...

  • 文件存储

    1)打开文件: 在python中用open()这个函数来打开文件并返回文件对象,open()函数有很多参数,其中第...

  • 14.Python之文件操作

    Python之文件操作 文件操作通过Python中的内置函数open()对文件进行操作。文件操作需要如下几个参数:...

  • 2018-06-30 Python File

    python with as的用法 Python open() 函数

  • python之文件操作

    1 创建 Python 使用 open() 函数创建或打开文件,语法格式如下所示: 参数说明如下所示: file:...

  • open()函数

    一、Python open()函数文件打开操作打开文件会用到open函数,标准的python打开文件语法如下:op...

  • open()

    一、Python open()函数文件打开操作 打开文件会用到open函数,标准的python打开文件语法如下:o...

  • linux c_常用函数

    open函数 open参数以及返回值 open函数可以打开或者创建文件, 使用命令man 2 open 可以在ma...

  • LPTHW NOTES 3

    11/3 python 1. open() 函数 open ( filename [, mode [, buffe...

网友评论

      本文标题:python open函数newline参数

      本文链接:https://www.haomeiwen.com/subject/kuezmrtx.html