新書

速遞

吳老的java版《selenium webdriver 實戰寶典》和python版《selenium Webdriver 3.0 自動化測試框架實戰指南》出版了,代碼拿來就能用。

文 | 黎扶澈

python file tell()

函數

在windows與mac上的差異

0

1

file tell( )

方法

tell( )

方法返迴文件的游標位置,即文件指針當前位置。

0

2

遇到的問題

在使用中發現:同樣的.txt文件內容和.py文件,在Mac上和Windows上運行的結果不同,

即tell()返回的結果不一致。

測試文件內容如下

good evening!ryroad212

測試代碼如下

with open("file.txt", "r", encoding="utf-8") as fp:    print(fp.tell())    print(fp.readline())    print(fp.tell())    print(fp.readline())    print(fp.tell())

在windows上

運行結果如下:

在mac上

運行結果如下:

0

3

問題出現的原因

為了弄清楚為什麼

tell( )

方法在windows與mac上返回的結果不一致,我們分別在windows和mac上運行如下代碼:

import osos.lineseplen(os.linesep)

 

windows

運行結果:

mac

運行結果:

Tips:os.linesep返回當前平台使用的行終止符。

如上圖所示,

Windows使用"
",Mac使用"
"。

官網解釋為「The string used to separate (or, rather, terminate) lines on thecurrent platform. 」

綜上所述,tell()方法在windows與mac上返回的結果不一致的原因是:

windows平台

上,文件第一行「goodevening!"

其實等於"goodevening!

",共15個字元

,而tell()是從0開始計算的,所以在讀取完第一行後,游標指向文件第二行的首個字元"r",所以返回15。

mac平台

上,文件第一行「goodevening!"

其實等於"goodevening!
",共14個字元

,所以返回14。

0

4

擴展內容

微軟的自帶記事本程序notepad.exe會給

UTF-8編碼的文件頭加入三個隱藏的位元組(即BOM)

。就是為了讓編輯器不去猜測文件本身是ASCII碼還是UTF-8。

所以會出現以下情況:

tell()返回18,由正常的15+3個隱藏BOM位元組組成。

使用notepad++編輯,將文件保存為utf-8 without BOM,即可解決此問題。

(The End)

文章發不發我說了算,

代碼練不練你說了算,

工資漲不漲領導說了算!

草根在測試行業如何殺出一條血路(2)

點此鏈接了解

2018web測試開發培訓一年期周六班!

喜馬拉雅

app搜索並

收聽「

光榮之路

」電台

光榮之路

招聘|徵稿|合作

|QQ群

[email protected]

python群:457561756

性能群:415987441

招聘群:203715128

感謝認真閱讀的你!

?

推薦閱讀:

相关文章