关于换行符的识别问题,在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!\r\n :

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


>>> # Newline translation disabled
>>> g = open('hello.txt', 'rt', newline='')
>>> g.read()
'hello world!\r\n''

 

相关文章:

  • 2022-12-23
  • 2021-07-23
  • 2022-12-23
  • 2021-09-16
  • 2021-11-23
  • 2022-12-23
  • 2022-01-15
  • 2022-01-07
猜你喜欢
  • 2022-02-09
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-04
  • 2021-08-12
相关资源
相似解决方案