關於換行符的識別問題,在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''