在Python中操作檔案之seek()方法的使用

來源:互聯網
上載者:User
這篇文章主要介紹了在Python中操作檔案之seek()方法的使用教程,是Python入門學習中的基礎知識,需要的朋友可以參考下

seek()方法在位移設定該檔案的當前位置。參數是可選的,預設為0,這意味著絕對的檔案定位,它的值如果是1,這意味著尋求相對於當前位置,2表示相對於檔案的末尾。

沒有傳回值。需要注意的是,如果該檔案被開啟或者使用'a'或'A+'追加,任何seek()操作將在下次寫撤消。

如果該檔案只開啟使用“a”的追加模式寫,這種方法本質上是一個空操作,但讀使能(模式'a+'),它仍然在追加模式開啟的檔案非常有用。

如果該檔案在文字模式下使用“t”,只有tell()返回的位移開都是合法的。使用其他位移會導致不確定的行為。

請注意,並非所有的檔案對象都是可搜尋。
文法

以下是seek()方法的文法:


fileObject.seek(offset[, whence])


參數

  • offset -- 這是在檔案中,讀/寫指標的位置。

  • whence -- 這是可選的,預設為0,這意味著絕對的檔案定位,其它的值是1,這意味著尋求相對於當前位置,2表示相對於檔案的末尾。

傳回值

此方法不返回任何值。
例子

下面的例子顯示了seek()方法的使用。


#!/usr/bin/python# Open a filefo = open("foo.txt", "rw+")print "Name of the file: ", fo.name# Assuming file has following 5 lines# This is 1st line# This is 2nd line# This is 3rd line# This is 4th line# This is 5th lineline = fo.readline()print "Read Line: %s" % (line)# Again set the pointer to the beginningfo.seek(0, 0)line = fo.readline()print "Read Line: %s" % (line)# Close opend filefo.close()


當我們運行上面的程式,它會產生以下結果:


Name of the file: foo.txtRead Line: This is 1st lineRead Line: This


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.