python 换行符的识别问题,Unix 和Windows 中是不一样的
關(guān)于換行符的識(shí)別問題,在Unix 和Windows 中是不一樣的(分別是n 和rn)。默認(rèn)情況下,Python 會(huì)以統(tǒng)一模式處理換行符。這種模式下,在讀取文本的時(shí)候,Python 可以識(shí)別所有的普通換行符并將其轉(zhuǎn)換為單個(gè)nn 字符。類似的,在輸出時(shí)會(huì)將換行符nn 轉(zhuǎn)換為系統(tǒng)默認(rèn)的換行符。如果你不希望這種默認(rèn)的處理方式,可以給open() 函數(shù)傳入?yún)?shù)newline='' ,就像下面這樣:
# Read with disabled newline translation
with open('somefile.txt', 'rt', newline='') as f:
...
為了說明兩者之間的差異,下面我在Unix 機(jī)器上面讀取一個(gè)Windows 上面的文本文件,里面的內(nèi)容是hello world!\r\n :
| 1 2 3 4 5 6 7 8 9 10 | >>>?# 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'' |
總結(jié)
以上是生活随笔為你收集整理的python 换行符的识别问题,Unix 和Windows 中是不一样的的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Cygwin编译W600 sdk
- 下一篇: SPIFFS文件系统移植–基于STM32