python 换行符的识别问题,Unix 和Windows 中是不一样的

关于换行符的识别问题,在Unix 和Windows 中是不一样的(分别是n 和rn)。默认情况下,Python 会以统一模式处理换行符。这种模式下,在读取文本的时候,Python 可以识别所有的普通换行符并将其转换为单个nn 字符。类似的,在输出时会将换行符nn 转换为系统默认的换行符。如果你不希望这种默认的处理方式,可以给open() 函数传入参数newline='' ,就像下面这样:
# Read with disabled newline translation
with open('somefile.txt', 'rt', newline='') as f:
...
为了说明两者之间的差异,下面我在Unix 机器上面读取一个Windows 上面的文本文件,里面的内容是hello world! :

>>> # Newline translation enabled (the default)
>>> f = open('hello.txt', 'rt')
>>> f.read()
'hello world!



>>> # Newline translation disabled
>>> g = open('hello.txt', 'rt', newline='')
>>> g.read()
'hello world!
''
原文地址:https://www.cnblogs.com/baxianhua/p/10190486.html